[英]How can I write each row to a csv file?
I currently have code that is writing to a csv file, however, it keesp replacing the first row of the file and overwriting it instead of writing of it.我目前有正在写入 csv 文件的代码,但是,它不断替换文件的第一行并覆盖它而不是写入它。
NOTE: I have this function inside a for loop inside main().注意:我在 main() 内的 for 循环中有这个 function。
def write_csv_report(filename, region, data, current, server1, server2=False):
if not os.path.exists(os.path.dirname(filename)):
try:
dir = os.makedirs(os.path.dirname(filename))
header = ['region','old_dns_server', 'proposed_dns_server1', 'proposed_dns_server2']
data = [region, current, server1, server2]
with open(filename, 'a') as file:
writer = csv.writer(file)
writer.writerow(header)
writer.writerow(data)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
When I run this function in my script, it writes to the file but only one entry is added.当我在脚本中运行此 function 时,它会写入文件,但只添加一个条目。
Is there any suggestions or solution where I can add multiple entries?有什么建议或解决方案可以添加多个条目吗? I have looked at other sage questions and googled but it looks like I already have the necessary changes needed to achieve this outcome, not sure what I'm missing.
我查看了其他圣人问题并进行了谷歌搜索,但看起来我已经进行了实现此结果所需的必要更改,但不确定我缺少什么。
For csv.writer
(and csv.reader
), you need to open the file with newline=''
.对于
csv.writer
(和csv.reader
),您需要使用newline=''
打开文件。
You also write the header every time, which is a bit odd.你还每次都写 header,这有点奇怪。
Here's a minimal example that does more-or-less what you want:这是一个或多或少做你想要的最小示例:
import csv
header = ['region','old_dns_server', 'proposed_dns_server1', 'proposed_dns_server2']
data1 = ['foo', 'bar', 'bar', 'quux']
data2 = ['foo1', 'bar1', 'bar1', 'quux2']
filename = 'test.csv'
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(header)
writer.writerow(data1)
with open(filename, 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(data2)
giving:给予:
region,old_dns_server,proposed_dns_server1,proposed_dns_server2
foo,bar,bar,quux
foo1,bar1,bar1,quux2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.