python萌新,记录一下,自己做项目时遇到需批量将txt文件转为excel文件。
代码如下:
`# coding:utf-8
import pandas as pd
import os
def get_path(file_path):
path_list = []
xls_list = []
file_list = os.listdir(file_path)
file_list.sort(key=lambda x: int(x[:2])) # 对读取的文件进行排序
for filename in file_list:
complete_path = os.path.join(file_path, filename)
path_list.append(complete_path)
for path in path_list:
f = open(path, ‘r’)
tr = pd.read_table(f)
xls_name = (path.split(’\’)[-1]).split(’.’)[0]
xls_path = ‘G:/PTME/data/new/’+xls_name+’.xls’
tr.to_excel(xls_path, header=None)
xls_list.append(xls_path)
return xls_list
if name == ‘main’:
p = ‘G:/PTME/data/DW’
print(get_path§)`
Python新手批量转换txt到Excel:自动化操作脚本解析
本文档介绍了Python初学者如何使用pandas库实现txt文件到Excel的批量转换,通过os模块遍历文件夹,对文件进行排序并逐个读取,最终保存为.xls格式。
1万+

被折叠的 条评论
为什么被折叠?



