Python kullanarak txt dosyası Excel'e dönüştür

Dec 14 2020

Her biri birden çok veri satırı içeren 5000'den fazla metin dosyam var. Hepsini tek bir MS Excel dosyasında birleştirmek istiyorum, böylece her dosyanın ilk satırı ilk sütuna girilir ve her dosyanın kalan satırları ikinci sütuna girilir.

Bunu python kullanarak nasıl yapabilirim?

Yanıtlar

JeffUK Dec 14 2020 at 08:42

İşte size bir örnek:

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

verir

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