python-读取目录下所有txt文件并转化为一个excel的多个sheet

读取目录下的所有文件的代码如下。

import os
for root, dirs, files in os.walk('./TXT转excel'):  
    print(root) #当前目录路径  
    print(dirs) #当前路径下所有子目录  
    print(files) #当前路径下所有非目录子文件

将目录下的所有txt文件存入一个excel中,每个txt存入到一个sheet里,分隔符为逗号。

import os
import pandas as pd

writer = pd.ExcelWriter("my_excel.xls", engine='openpyxl')#我要生成的excel的文件路径是my_excel.xls
num = 1
for root, dirs, files in os.walk('./TXT转excel'):  
    print(root) #当前目录路径  
    print(dirs) #当前路径下所有子目录  
    print(files) #当前路径下所有非目录子文件
    for file in files:
        tmp=pd.read_csv("./TXT转excel/%s"%(file),sep=',')
        tmp.to_excel(excel_writer=writer, sheet_name=file)
    writer.save()

猜你喜欢

转载自blog.csdn.net/nanfeizhenkuangou/article/details/119768026