Convertir archivo txt a Excel usando python

Dec 14 2020

Tengo más de 5000 archivos de texto, cada uno con varias líneas de datos. Quiero fusionarlos todos en un archivo de MS Excel para que la primera línea de cada archivo se ingrese en la primera columna y las líneas restantes de cada archivo se ingresen en la segunda columna.

¿Cómo puedo hacer esto usando Python?

Respuestas

JeffUK Dec 14 2020 at 08:42

Aquí tienes un ejemplo:

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

da

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