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)

这里:

  1. parent 将提供父目录信息。
  2. absolute 将给出绝对路径
  3. stem 将给出没有扩展名的文件名
  4. name 将给出文件的名称。

注意:如果您只需要文件信息,您可以在 list comprehension : if f.is_file() 中添加一个 if 条件。