【发布时间】:2021-05-19 17:22:52
【问题描述】:
我想保存所有目录信息。 (路径、文件夹、子文件夹和文件)到使用 Pandas 的 Excel 电子表格。
到目前为止,这是我的代码:
import os
import pandas as pd
# setup the paths
root_path = os.path.join(os.path.expanduser("~"), 'Desktop/')
test_path = os.path.join(root_path, 'Test Dir')
# setup excelwriter
# Input writer
xlWriterOutput = pd.ExcelWriter(os.path.join(test_path,'read_directory_to_excel.xlsx'), engine='xlsxwriter')
files_list = []
dfFiles = pd.DataFrame
directory_path = os.path.join(root_path, test_path)
if not os.path.exists(directory_path):
message = "Failed to find directory '%s'." % path
if errors is not None:
errors.append(message)
else:
raise IOError(message)
else:
for path, dirs, files in os.walk(test_path):
for file in files:
files_list.append(os.path.join(path,file))
dfFiles['path'] = path
dfFiles['directory'] = dirs
dfFiles['file_name'] = file
#Write the directory walk out to excel
dfFiles.to_excel(xlWriterOutput, header=True, sheet_name='Directory Output', index=False)
我从一个列表开始,但开始将我的解决方案转移到 Pandas 和 ExcelWriter。我在尝试设置dfFiles['path'] = path 的行上收到错误“类型错误:'type' 对象不支持项目分配”。此时需要一些帮助。
【问题讨论】: