将数据写入一个csv行Python

时间:2013-08-23 14:46:57

标签: python csv

在我的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行,并将模式分成不同的行?

谢谢!

1 个答案:

答案 0 :(得分:1)

从首先读取的行中删除尾部换行符。