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§)`