Chuyển đổi tệp txt sang Excel bằng python

Dec 14 2020

Tôi có hơn 5000 tệp văn bản, mỗi tệp có nhiều dòng dữ liệu. Tôi muốn hợp nhất tất cả chúng thành một tệp MS Excel để dòng đầu tiên của mỗi tệp được nhập vào cột đầu tiên và các dòng còn lại của mỗi tệp được nhập vào cột thứ hai.

Làm thế nào tôi có thể làm điều này bằng cách sử dụng python?

Trả lời

JeffUK Dec 14 2020 at 08:42

Đây là một ví dụ cho bạn:

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

cho

Column 1 Heading,Column 2 Heading
bob,1
,1
,1
,1
,1
,1