【问题标题】:Using os.walk to get all files from dir and its subdirs [duplicate]使用 os.walk 从 dir 及其子目录中获取所有文件 [重复]
【发布时间】:2018-06-04 06:47:33
【问题描述】:

我目前正在编写一个 python 脚本,你可以给它一个驱动器或文件夹,然后它会遍历驱动器或文件夹上的每个图像并将它们全部移动到一个文件夹中。

我的问题是使用 os.walk,它不会自动打开子目录。例如,假设我选择了 E: 驱动器进行扫描。 E:驱动文件结构;

E:
   + Folder1
       - file.png
       - file2.png
   - files.jpg

我的脚本将检测到的唯一文件是 files.jpg,因为其他文件嵌套在子目录中,os.walk 不会打开并检查文件。

这是我现在使用的代码;

# For each file in the drive
    for folders, sub_folders, files in os.walk(drive):
        # For each name in the files
        for filename in files:
            if filename == drive + "\\ImageSorter\\":
                continue

            file_name = os.path.splitext(filename)[0]
            extension = os.path.splitext(filename)[1]

有没有办法让 os.walk 遍历驱动器上的所有子目录,而不仅仅是第一个文件夹?

【问题讨论】:

标签: python os.walk


【解决方案1】:

试试这个代码

import os
for root, dirs, files in os.walk("."):
    path = root.split(os.sep)
    print((len(path) - 1) * '---', os.path.basename(root))
    for file in files:
        print(len(path) * '---', file)

【讨论】:

  • 你为什么要提出一个副本然后同时回答?
  • 你真的应该相信正确的问题
猜你喜欢
  • 2012-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-29
  • 2011-08-19
  • 2017-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多