如何使用python将csv文件转换为文本文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47339698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert csv file to text file using python?
提问by B_R
I want to convert a couple of .csv files to .txt files using python. In my .csv files, I have hundreds of lines of data like the bellow: image of the csv file
我想使用 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
I use the bellow code for this purpose.
为此,我使用了波纹管代码。
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.')
My first problem is that when the name of the input file is (for example) "DFW002_0330PM_Thursday_November_16_2017", I get the bellow error:
我的第一个问题是,当输入文件的名称是(例如)“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
But, when I change the name of the code to (for example) "11", the code defines the file and goes to the next steps, but again it returns the bellow error:
但是,当我将代码名称更改为(例如)“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
Would you please help me handle these problems?
你能帮我处理这些问题吗?
回答by loretoparisi
Using csv
it's very easy to iterate over the csv lines:
使用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()