如何使用python将csv文件转换为文本文件?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何使用python将csv文件转换为文本文件?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2255字,纯文字阅读大概需要4分钟。
内容图文
![如何使用python将csv文件转换为文本文件?](/upload/InfoBanner/zyjiaocheng/735/2623fd730f354d18bef3881e00eac6b1.jpg)
参见英文答案 > input() error – NameError: name ‘…’ is not defined 11个
我想使用python将几个.csv文件转换为.txt文件.在我的.csv文件中,我有数百行数据,如下:
image of the csv file
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可以很容易地迭代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()
内容总结
以上是互联网集市为您收集整理的如何使用python将csv文件转换为文本文件?全部内容,希望文章能够帮你解决如何使用python将csv文件转换为文本文件?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。