File txt convertito in Excel utilizzando python
Dec 14 2020
Ho più di 5000 file di testo, ciascuno con più righe di dati. Voglio unirli tutti in un file MS Excel in modo che la prima riga di ogni file sia inserita nella prima colonna e le righe rimanenti di ogni file siano inserite nella seconda colonna.
Come posso farlo usando Python?
Risposte
JeffUK Dec 14 2020 at 08:42
Ecco un esempio per te:
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
dà
Column 1 Heading,Column 2 Heading
bob,1
,1
,1
,1
,1
,1