Pythonを使用してExcelに変換するTxtファイル

Dec 14 2020

5000を超えるテキストファイルがあり、それぞれに複数行のデータがあります。それらすべてを1つのMSExcelファイルにマージして、各ファイルの最初の行が最初の列に入力され、各ファイルの残りの行が2番目の列に入力されるようにします。

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