2017-11-16 1 views
1

파이썬을 사용하여 .csv 파일을 .txt 파일로 변환하려고합니다. image of the csv filecsv 파일을 파이썬을 사용하여 텍스트 파일로 변환하는 방법은 무엇입니까?

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 파일에서, 나는 울부 짖는 소리 등의 데이터 라인의 수백이있다. 나는의 이름을 변경할 때,

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 

그러나 :

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"(예를 들어) 때, 나는 울부 짖는 오류가 있다는 것입니다 "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 

당신이 날이 문제를 처리하는 데 도움시겠습니까은?

+0

이유를 예를 쉼표를하지 않는 이유는 무엇입니까? 그것은 의도적이거나 실수 한 것입니다. 쉼표없이 CSV가 될 수 있습니까? 나는 무엇을 여기에서 놓치고 있냐? – PYA

+0

CSV 파일에서이 데이터를 복사하여 여기에 복사 했으므로 아마도 다음과 같이 표시됩니다. 파일이나 이미지를 업로드 할 수 있다면 그 파일을 볼 수 있습니다. –

+1

어떤 줄이 당신에게'TypeError'를줍니다 – PYA

답변

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() 
관련 문제