[英]Python: How can I create a data file from a converted csv file?
I am trying to convert a csv file into another file (file type doesn't matter as the program using the converted data just opens it like a text file). 我正在尝试将一个csv文件转换为另一个文件(文件类型无关紧要,因为使用转换后的数据的程序只会像文本文件一样打开它)。
So far I have managed to convert and print the original csv data into the the data structure I want but I now need to save that as another file. 到目前为止,我已经设法将原始的csv数据转换并打印到所需的数据结构中,但是现在我需要将其另存为另一个文件。
import csv
file = open('newData', 'w')
with open('initialData.csv', 'rb') as f:
reader = csv.reader(f, delimiter=',', quotechar='|')
for row in reader:
print row[13] + ' 1:' + row[0] + ' 2:' + row[1]
file.write(f)
file.close()
Whenever I run this I get the error: 每当我运行此命令时,我都会收到错误消息:
TypeError: expected a character buffer object
I know there is nothing wrong with converting the csv file as that prints fine when I comment out the file.write(f). 我知道转换csv文件没有任何问题,因为当我注释掉file.write(f)时,它可以正常打印。
Many thanks in advance! 提前谢谢了!
Why are you trying to write the original file (the f
object) to the new file? 为什么要尝试将原始文件(
f
对象)写入新文件? Don't you want to write the re-formatted data? 您是否不想写入重新格式化的数据?
import csv
with open('initialData.csv', 'rb') as f_in, open('newData', 'w') as f_out:
reader = csv.reader(f_in, delimiter=',', quotechar='|')
for row in reader:
print row[13] + ' 1:' + row[0] + ' 2:' + row[1]
f_out.write(row[13] + ' 1:' + row[0] + ' 2:' + row[1])
Edit: as suggested by Jon Clements, use context manager for output as well + indentation fix. 编辑:根据乔恩·克莱门茨(Jon Clements)的建议,使用上下文管理器进行输出以及缩进修复。
You're trying to print out the file handle for the whole csv file. 您正在尝试打印出整个csv文件的文件句柄。 I'm guessing you want the text you're printing to be written out into a file, in that case just do:
我猜您希望将要打印的文本写到文件中,在这种情况下,请执行以下操作:
with open('initialData.csv', 'rb') as infile, open('newData.txt') as outfile:
reader = csv.reader(infile, ...)
for row in reader:
outfile.write(row[13] + ' 1:' + row[0] + ' 2:' + row[1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.