如何解决Python/Pandas 遍历目录并将所有文件夹名子文件夹和文件保存到 excel
我想保存所有目录信息。 (路径、文件夹、子文件夹和文件)到使用 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
的行上收到错误“类型错误:'类型'对象不支持项目分配”。此时需要一些帮助。
解决方法
您可以使用pathlib module
:
from pathlib import Path
inp_path = Path('.') # specify the path here
df = pd.DataFrame([{'parent': f.absolute().parent,'full_path': f.absolute(),'relative_path': f,'file_name_without_extension': f.stem,'file_name_with_extension': f.name} for f in inp_path.glob('**/*')])
df.to_excel('specify the excel sheet path here.xsls',index = False)
这里:
-
parent
将提供父目录信息。 -
absolute
将给出绝对路径 -
stem
将给出没有扩展名的文件名 -
name
将给出文件的名称。
注意:如果您只需要文件信息,您可以在 list comprehension
: if f.is_file()
中添加一个 if 条件。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。