【问题标题】:Python/Pandas Walk through directory and save all foldernames subfolder and file to excelPython/Pandas 遍历目录并将所有文件夹名子文件夹和文件保存到 excel
【发布时间】: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' 对象不支持项目分配”。此时需要一些帮助。

【问题讨论】:

    标签: python pandas os.walk


    【解决方案1】:

    你可以使用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 条件:if f.is_file()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-20
      • 2018-05-22
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多