Python 将数据写入一个csv行
在我的py脚本中,我需要将数据写入一个csv文件,结果是每行五列Python 将数据写入一个csv行,python,csv,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
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\u file.write(“%r\n%r\n%r\n%”(一、三、四))
和变体,但数据的工作方式与我所需要的不同
我不知道我的代码哪里错了。我认为.write()
会将数据写入同一行,除非另有规定(以前的使用)
问题:我如何.write()
将模式的一行写入一个csv行,并且仍然将模式分隔为不同的行
谢谢 首先从读取的行中删除尾随的换行符。非常感谢!由于某种原因,我总是忘记尾随的换行符而遇到同样的问题!