-1

I have more than 5000 text files, each with multiple lines of data. I want to merge all of them into one MS Excel file so that the first line of each file is entered into the first column and the remaining lines of each file are entered into the second column.

How can I do this using python?

3
  • Does this your question stackoverflow.com/questions/36557058/… Commented Dec 13, 2020 at 19:19
  • 1
    And your data sample. Please give a MRE so that people can actually help you Commented Dec 13, 2020 at 19:19
  • Honestly, aim to convert them into CSV rather than XLSX, it's a lot easier and CSVs are supported by excel. You should be able to find some thing on google for "How to read from text files" and "how to create CSV files in python." Commented Dec 14, 2020 at 1:25

1 Answer 1

0

Here's an example for you:

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

gives

Column 1 Heading,Column 2 Heading
bob,1
,1
,1
,1
,1
,1
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much dear ....i will try this ...thanks again ....tc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.