Python을 사용하여 TXT 파일을 Excel로 변환
Dec 14 2020
각각 여러 줄의 데이터가있는 5000 개 이상의 텍스트 파일이 있습니다. 각 파일의 첫 번째 줄이 첫 번째 열에 입력되고 각 파일의 나머지 줄이 두 번째 열에 입력되도록 모든 파일을 하나의 MS Excel 파일로 병합하고 싶습니다.
파이썬을 사용하여 어떻게 할 수 있습니까?
답변
JeffUK Dec 14 2020 at 08:42
다음은 귀하를위한 예입니다.
import csv
filename = "demofile.txt"
#Read the file into a list
with open(filename) as f:
content = f.readlines()
#strip out any spaces and new-line characters from the end of each row
content = [x.rstrip() for x in content]
#open a CSV file for writing
with open('output.csv', 'w', newline='') as csvfile:
#Setup the CSV File
csvwriter= csv.writer(csvfile)
#Label the Columns
csvwriter.writerow(['Column 1 Heading' , 'Column 2 Heading'])
#Write the Tricky bit where you transpose the first row
csvwriter.writerow([content[0],content[1]])
#Write the rest
for row in content[2:]:
csvwriter.writerow(['',content[1]])
demofile.txt
bob
1
2
3
4
5
6
준다
Column 1 Heading,Column 2 Heading
bob,1
,1
,1
,1
,1
,1