如何使用Python将CSV文件转换为文本文件?

6
我想使用Python将几个.csv文件转换为.txt文件。在我的.csv文件中,有数百行数据,如下所示:csv文件的图片
Value   Date    Time
919     4/15/2016   19:41:02
551     4/15/2016   19:46:51
717     4/15/2016   19:49:48
2679    4/15/2016   19:52:49
2890    4/15/2016   19:55:43
2897    4/15/2016   19:58:38
1790    4/15/2016   21:39:14
2953    4/15/2016   21:42:10
2516    4/15/2016   21:45:04
2530    4/15/2016   21:47:58
2951    4/15/2016   21:51:02
2954    4/15/2016   21:53:56
2537    4/15/2016   21:56:52
2523    4/15/2016   21:59:45
2536    4/15/2016   22:02:49
2727    4/15/2016   22:05:43

我使用下面的代码来实现这个目的。
csv_file = input('Enter the name of your input file: ')
txt_file = input('Enter the name of your output file: ')

text_list = []

with open(csv_file, "r") as my_input_file:
    for line in my_input_file:
        line = line.split(",", 2)
        text_list.append(" ".join(line))

with open(txt_file, "w") as my_output_file:
    my_output_file.write("#1\n")
    my_output_file.write("double({},{})\n".format(len(text_list), 2))
    for line in text_list:
        my_output_file.write("  " + line)
    print('File Successfully written.')

我的第一个问题是,当输入文件的名称为“DFW002_0330PM_Thursday_November_16_2017”时,我收到以下错误:

Traceback (most recent call last):
  File "C:/Users/Behzad/Desktop/run/UTA/cvstotext.py", line 1, in <module>
    csv_file = input('Enter the name of your input file: ')
  File "<string>", line 1, in <module>
NameError: name 'DFW000_0330PM_Thursday_November_16_2017' is not defined

但是,当我将代码名称更改为(例如)“11”时,该代码会定义文件并执行下一步操作,但仍会返回以下错误:

Traceback (most recent call last):
  File "C:/Users/Behzad/Desktop/run/UTA/cvstotext.py", line 6, in <module>
    with open(csv_file, "r") as my_input_file:
TypeError: coercing to Unicode: need string or buffer, int found

你能帮我处理这些问题吗?


你的示例为什么没有逗号?这是故意还是错误。如果没有逗号,它就不能算作 CSV 文件,对吧?我在这里漏掉了什么? - PYA
我把这些数据从CSV文件中复制到这里,可能因为这个原因,它显示成这样。如果我可以上传文件或图片,你就可以看到了。 - B_R
1
哪一行代码会导致 TypeError 错误? - PYA
针对那个错误,请尝试使用以下代码:csv_file = str(input('请输入输出文件名:')) 将您的输入转换为字符串,或许可以解决问题。 - PYA
1
Python 2.x:input()正在尝试评估您的输入,这就是为什么您会收到NameError的原因。请改用raw_input()。这是一个重复的问题。 - wwii
显示剩余5条评论
1个回答

21

使用csv,迭代csv行非常容易:

import csv
csv_file = raw_input('Enter the name of your input file: ')
txt_file = raw_input('Enter the name of your output file: ')
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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接