简体   繁体   English

Python csv没有写入文件

[英]Python csv not writing to file

I am trying to write to a .tsv file using python's CSV module, this is my code so far 我正在尝试使用python的CSV模块写入.tsv文件,这是我的代码到目前为止

file_name = "test.tsv"
TEMPLATE = "template.tsv"
fil = open(file_name, "w")
# Added suggested change 
template = csv.DictReader(open(TEMPLATE, 'r'), delimiter='\t')
new_file = csv.DictWriter(fil, fieldnames=template.fieldnames, delimiter='\t')
new_file.writeheader()

basically TEMPLATE is a file that will contain the headers for the file, so i read the headers using DictReader and pass the fieldnames to DictWriter , as far as i know the code is fine, the file test.tsv is being created but for some reason the headers are not being written. 基本上TEMPLATE是一个包含文件头的文件,所以我使用DictReader读取头文件并将字段名传递给DictWriter ,据我所知代码很好,文件test.tsv正在创建但由于某种原因标题没有被写入。

Any help as to why this is happening is appreciated, thanks. 任何有关为什么会发生这种情况的帮助表示赞赏,谢谢。

DictReader's first argument should be a file object (create with open() ), cf. DictReader的第一个参数应该是一个文件对象(用open()创建),参见 http://docs.python.org/py3k/library/csv.html#csv.DictReader http://docs.python.org/py3k/library/csv.html#csv.DictReader

You forgot open() for the TEMPLATE file. 您忘记了TEMPLATE文件的open()

import csv

file_name = "test.tsv"
TEMPLATE = "template.tsv"
fil = open(file_name, "w")

# you forgot this line, which will open the file
template_file = open(TEMPLATE, 'r')

template = csv.DictReader(template_file, delimiter='\t')
new_file = csv.DictWriter(fil, fieldnames=template.fieldnames, delimiter='\t')
new_file.writeheader()

Try to give DictReader opened file instead of file name: 尝试给DictReader打开文件而不是文件名:

csv.DictReader(open(TEMPLATE, 'r'), delimiter='\t')

Same for the writer, but opened for writing. 同样是作家,但开始写作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM