我是Python编程的新手,最近我正在尝试读取csv文件,然后将该csv文件中的数据保存到文本文件中。这是我正在使用的代码
csv_file = open('example.csv', 'r')
txt_file = open('example.txt', 'w')
with open(txt_file, 'w') as my_output_file:
with open(csv_file, 'r') as my_input_file:
[my_output_file.write(" ".join(row)+'\n') for row in csv.reader(my_input_file)]
my_output_file.close()
我收到此错误
File "c:\Users\Desktop\Folder\tokenizing.py", line 41, in <module>
with open(txt_file, 'w') as my_output_file:
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
有谁知道为什么抱怨?
答案 0 :(得分:0)
将文件名传递给open调用并使用for循环而不是list comp,并让文件对象的with context manager负责关闭文件:
csv_file = 'example.csv'
txt_file = 'example.txt'
with open(txt_file, 'w') as my_output_file:
with open(csv_file, 'r') as my_input_file:
for row in csv.reader(my_input_file):
my_output_file.write(" ".join(row)+'\n')