【问题标题】:How to convert csv file to text file using python? [duplicate]如何使用python将csv文件转换为文本文件? [复制]
【发布时间】:2018-04-30 14:01:08
【问题描述】:

我想使用 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文件中复制了这些数据并复制到这里,可能正因为如此,它才显示为这样。如果我可以上传文件或图片,您可以看到。
  • 哪一行给你TypeError
  • 请将完整的 Traceback 格式化为代码。
  • Python 2.x: input() 正在尝试评估您的 input 这就是您收到 NameError 的原因。请改用raw_input()。这是一个重复的问题。

标签: python csv text


【解决方案1】:

使用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()

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 1970-01-01
    • 2021-11-21
    • 2016-03-08
    • 2019-12-01
    • 1970-01-01
    • 2019-04-28
    • 2017-11-05
    • 1970-01-01
    相关资源
    最近更新 更多