python 用于拆分所有行并保存在新的输出文件中
python for split all line and save in new output file
我已经有了这个代码
#!usr.bin/env pyhton
asal = open("honeyd.txt")
tujuan = open("test.rule", "W")
satu = asal.readline()
a = satu.split();
b = 'alert ' + a[0]+' ' + a[1] + ' -> ' + a[2]+' '+ a[3]
c = str(b)
tujuan.write(c)
asal.close()
tujuan.close()
但是这段代码只是读取一行并拆分它。
实际上,我的 "honeyd.txt" 中有 3 行
我的目标是拆分所有行。
如何拆分所有行并将其保存到"test.rule"?
您需要遍历输入行;现在你只调用 readline
一次。最好直接循环输入文件句柄:
with open('honeyd.txt') as infile, open('test.rule', 'w') as outfile:
for line in infile:
outfile.write('alert {} {} -> {} {}'.format(*line.split())
另请注意 with
语句的使用,这样您就不必手动调用 close
。
我已经有了这个代码
#!usr.bin/env pyhton
asal = open("honeyd.txt")
tujuan = open("test.rule", "W")
satu = asal.readline()
a = satu.split();
b = 'alert ' + a[0]+' ' + a[1] + ' -> ' + a[2]+' '+ a[3]
c = str(b)
tujuan.write(c)
asal.close()
tujuan.close()
但是这段代码只是读取一行并拆分它。 实际上,我的 "honeyd.txt" 中有 3 行 我的目标是拆分所有行。
如何拆分所有行并将其保存到"test.rule"?
您需要遍历输入行;现在你只调用 readline
一次。最好直接循环输入文件句柄:
with open('honeyd.txt') as infile, open('test.rule', 'w') as outfile:
for line in infile:
outfile.write('alert {} {} -> {} {}'.format(*line.split())
另请注意 with
语句的使用,这样您就不必手动调用 close
。