web-dev-qa-db-ja.com

Pythonを使用してcsvファイルをテキストファイルに変換する方法は?

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

これらの問題の処理を手伝っていただけませんか?

4
B_R

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()
10
loretoparisi