目的:获取“C:\Users\User\Desktop\归档”下的所有文件,截取文件名中一段字符串,作为dict的key,文件名作为dict的value,将这两列信息写入到Excel中。
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import pandas as pd
order_dict = {}
file_path = r'C:\Users\User\Desktop\归档'
for file_name in os.listdir(file_path):
abs_file_path=file_path+'\\'+ file_name
order_num = file_name[0:12]
order_dict[order_num] = abs_file_path
# print(order_dict)
df = pd.DataFrame.from_dict(order_dict,orient='index',columns=['file_path'])
df = df.reset_index().rename(columns = {'index':'order_num'})
writer = pd.ExcelWriter(r'C:\Users\User\Desktop\test.xlsx')
df.to_excel(r'C:\Users\User\Desktop\test.xlsx')
# print(df)
其中order_dict = {'YXGD19000770': 'C:\\Users\\User\\Desktop\\归档\\YXGD1900077.zip', 'YXGD19000404': 'C:\\Users\\User\\Desktop\\归档\\YXGD19000404.zip', 'YXGD19000400': 'C:\\Users\\User\\Desktop\\归档\\YXGD19000400.zip', 'YXGD19000797': 'C:\\Users\\User\\Desktop\\归档\\YXGD19000797.zip'}
其中df