簡體   English   中英

使用 python 將 Txt 文件轉換為 Excel

[英]Txt file convert to Excel using python

我有 5000 多個文本文件,每個文件都有多行數據。 我想將它們全部合並到一個 MS Excel 文件中,以便將每個文件的第一行輸入到第一列,將每個文件的其余行輸入到第二列。

如何使用 python 做到這一點?

這是給你的一個例子:

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]])

演示文件.txt

bob
1
2
3
4
5
6

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM