ไฟล์ Txt แปลงเป็น Excel โดยใช้ python

Dec 14 2020

ฉันมีไฟล์ข้อความมากกว่า 5,000 ไฟล์แต่ละไฟล์มีข้อมูลหลายบรรทัด ฉันต้องการรวมไฟล์ทั้งหมดเป็นไฟล์ MS Excel ไฟล์เดียวเพื่อให้บรรทัดแรกของแต่ละไฟล์ถูกป้อนลงในคอลัมน์แรกและบรรทัดที่เหลือของแต่ละไฟล์จะถูกป้อนลงในคอลัมน์ที่สอง

ฉันจะทำสิ่งนี้โดยใช้ python ได้อย่างไร?

คำตอบ

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