如何在Python中编辑* .txt或* .dat文件信息?

时间:2015-09-08 10:44:43

标签: python

我是Python的初学者,有下一个“问题”。我很高兴,如果你能帮助我的话)

我有一个* .dat文件(我们将其命名为 file-1 ,第一行只是一个标题,我只在这里用来标记列),如下所示:

1   2   3       4   5   6

6   5   -1000   ""  ""  ""
6   5   -1000   ""  ""  ""

6   5   -1000   ""  ""  ""

6   5   -1000   ""  ""  ""
6   5   -1000   ""  ""  ""
6   5   -1000   ""  ""  ""
6   5   -1000   ""  ""  ""

我需要它( file-1(已转换)):

6   5   1   -1000
6   5   1   -1000
6   5   2   -1000
6   5   3   -1000
6   5   3   -1000
6   5   3   -1000
6   5   3   -1000

因此,file-1有9行(7行有信息,2行空)和6列,我必须做下一行:

  1. 删除文件-1中的最后3列。
  2. 在第2列和第3列之间添加1个新列。
  3. 传递空行后,此新列的值应增加1个单位(如“+ = 1”)。
  4. 删除所有空行。结果表示为'file-1(转换)'。
  5. 我试过这样做但是坚持了下来。现在我处于以下水平:

    import sys
    import csv
    
    with open("file-1.dat", "r", newline="") as f:
        sys.stdout = open('%s2 (converted).txt' % f.name, 'a')
        incsv = csv.reader(f, delimiter="\t")
        for row in incsv:
            if len(row) == 6:
                i = 0
                row = row[0:3]
                row.insert(2, i)
                print(row)
    

    看起来像:

    ['6', '5', 0, '-1000']
    ['6', '5', 0, '-1000']
    
    ['6', '5', 0, '-1000']
    
    ['6', '5', 0, '-1000']
    ['6', '5', 0, '-1000']
    ['6', '5', 0, '-1000']
    ['6', '5', 0, '-1000']
    

    我现在还不知道如何将0改为1和2等等,所以它可能是这样的:

    ['6', '5', 0, '-1000']
    ['6', '5', 0, '-1000']
    
    ['6', '5', 1, '-1000']
    
    ['6', '5', 2, '-1000']
    ['6', '5', 2, '-1000']
    ['6', '5', 2, '-1000']
    ['6', '5', 2, '-1000']
    

    结果应该像'file-1(转换)'文件。

    P.S。所有的例子都是简化的,真正的文件有很多行,我不知道空行出现在哪里。

    P.P.S。对不起这么长的帖子,希望,这是有道理的。问,建议 - 我很高兴看到其他意见)谢谢。

3 个答案:

答案 0 :(得分:3)

似乎你几乎就在那里,你只是一直插入with open("file-1.dat", "r", newline="") as f: sys.stdout = open('%s2 (converted).txt' % f.name, 'a') incsv = csv.reader(f, delimiter="\t") empties = 0 # init empty row counter for row in incsv: if len(row) == 6: row = row[0:3] row.insert(2, empties) # insert number of empty rows print(row) else: empties += 1 # if row is empty, increase counter 而不是空行数,尝试类似:

from scapy.all import *
import datetime
import csv
import sys

PROBE_REQUEST_TYPE=0
PROBE_REQUEST_SUBTYPE=4

STAMP = datetime.datetime.now().isoformat()

WHITELIST = ['00:00:00:00:00:00',] # Replace this with your phone's MAC address


def PacketHandler(pkt):
if pkt.haslayer(Dot11):
    if pkt.type==PROBE_REQUEST_TYPE and pkt.subtype == PROBE_REQUEST_SUBTYPE and ( pkt.addr2.lower() not in WHITELIST or pkt.addr2.upper() not in WHITELIST):
        PrintPacket(pkt)

def PrintPacket(pkt):
print "Probe Request Captured:"
try:
    extra = pkt.notdecoded
except:
    extra = None
if extra!=None:
    signal_strength = -(256-ord(extra[-4:-3]))
else:
    signal_strength = -100
    print "No signal strength found"    
print "Target: %s Source: %s SSID: %s RSSi: %d"%(pkt.addr3,pkt.addr2,pkt.getlayer(Dot11ProbeReq).info,signal_strength)
f = open('/mtn/sda1/logger.csv', 'w')
filename = 'logger.csv'.format(STAMP)
    open(filename, 'a') as f:
           f.write('Target: %s Source: %s SSID: %s RSSi: %d"%(pkt.addr3,pkt.addr2,pkt.getlayer(Dot11ProbeReq).info,signal_strength)'.format(STAMP))
f.close()

def main():
from datetime import datetime
print "[%s] Starting scan"%datetime.now()
print "Scanning ..."
print "\n"
sniff(iface=sys.argv[1],prn=PacketHandler,store=0)

if __name__=="__main__":
main()

答案 1 :(得分:1)

您需要在每个空行

上增加i
import sys
import csv

with open("file-1.dat", "r") as f:
    sys.stdout = open('%s2 (converted).txt' % f.name, 'a')
    incsv = csv.reader(f, delimiter="\t")
    incsv.next() # ignore first line
    i = 0
    for row in incsv:
        if len(row) == 6:
            row = row[0:3]
            row.insert(2, i)
            print(row)
        elif len(row) == 0:
            i += 1

另外,我无法在我的机器上执行您的代码(使用Python 2.7.6)。我根据Python 2.x运行代码更改了代码。

修改:我看到它与Python 3.x

一起运行

答案 2 :(得分:1)

如果不使用csv模块,这有点不同。希望这可以帮助。 :)

import sys

count = 0
with open("file-1.dat", "r") as f:
    sys.stdout = open('%s2 (converted).txt' % f.name, 'a')
    for line in f:
        converted_line = line.split()[:-3] #split each line and remove last 3 column
        if not converted_line: # if list/line is empty
            count += 1 #increase count but DO NOT PRINT/ WRITE TO FILE
        else:
            converted_line.insert(2,str(count)) # insert between 2nd and 3rd column
            print ('\t'.join(converted_line)) # join them and print them with tab delimiter
相关问题