0

在我的 py 脚本中,我需要将数据写入 csv 文件,结果为每行五列。

title:info title title title title    
 one        two  three four  five
 one        two  three four  five
title:info title title title title 
 one        two  three four  five

如果可能的话,我想使用该file.write()方法,而不是 csv 模块。

for ip in open("list.txt"):
    with open("data.txt", "a") as csv_file:
        csv_file.write("\r Title:" + ip + ", Title, Title, Title, Title \r")
        for line in open("0820-oRG-apflog.txt"):
            new_line = line.split()
            #search apflog for correct lines
            if "blocked" in new_line:
                if "src="+ip.strip() in new_line:
                    #write columns to new text file & remove headers from lines in files and add commas
                    csv_file.write(ip + ", " + new_line[11].replace("dst=", ", ") + new_line[12].replace("proto=", ", "))
                    try:
                        csv_file.write(new_line[14].replace("dpt=", ", "))
                    except IndexError:
                        pass

当我运行脚本时,我得到了结果:

title:info
          title title title title
one
          two three four five

我已经尝试过:csv_file.write('%r\n%r\n%r\n' % (one, three, four))和变化,但是数据并没有按照我需要的方式工作。

我不知道我的代码哪里错了。我认为.write()除非另有说明(来自以前的用途),否则会将数据写入同一行。

问题:如何将.write()一行模式放入一个 csv 行,并且仍然将模式分成不同的行?

谢谢!

4

1 回答 1

1

从首先读取的行中去除尾随换行符。

于 2013-08-23T14:50:31.350 回答