【问题标题】:Python os.walk Include only specific foldersPython os.walk 仅包含特定文件夹
【发布时间】:2019-02-05 10:23:29
【问题描述】:

我正在编写一个 Python 脚本,它以日期的形式接受用户输入,例如 20180829,这将是一个子目录名称,然后它使用 os.walk 函数遍历特定目录,一旦到达该目录传入它会跳转到里面并查看其中的所有目录并在不同的位置创建一个目录结构。

我的目录结构将如下所示:

|dir1

|-----|dir2|

|-----------|dir3

|-----------|20180829

|-----------|20180828

|-----------|20180827

|-----------|20180826

所以 dir3 将有许多子文件夹,它们都是日期格式。我需要能够仅复制开始时传入的目录的目录结构,例如 20180829 并跳过其余目录。

我一直在网上寻找一种方法来做到这一点,但我只能找到从 os.walk 函数中排除目录的方法,如下面的线程: Filtering os.walk() dirs and files

我还发现了一个线程,它允许我打印出我想要的目录路径,但不会让我创建我想要的目录: Python 3.5 OS.Walk for selected folders and include their subfolders.

以下是我的代码,它打印出正确的目录结构,但在我不希望它做的新位置创建整个目录结构。

includes = '20180828'
inputpath = Desktop
outputpath = Documents

for startFilePath, dirnames, filenames in os.walk(inputpath, topdown=True):
    endFilePath = os.path.join(outputpath, startFilePath)
    if not os.path.isdir(endFilePath):
        os.mkdir(endFilePath)
    for filename in filenames:
        if (includes in startFilePath):
            print(includes, "+++", startFilePath)
            break

【问题讨论】:

  • if (includes in startFilePath): 去掉括号

标签: python recursion os.walk


【解决方案1】:

我不确定我是否理解您的需求,但我认为您将一些事情复杂化了。如果下面的代码对您没有帮助,请告诉我,我们会考虑其他方法。

我运行它来创建一个像你这样的例子。

# setup example project structure

import os
import sys

PLATFORM = 'windows' if sys.platform.startswith('win') else 'linux'
DESKTOP_DIR = \
    os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') \
    if PLATFORM == 'linux' \
    else os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

example_dirs = ['20180829', '20180828', '20180827', '20180826']

for _dir in example_dirs:
    path = os.path.join(DESKTOP_DIR, 'dir_from', 'dir_1', 'dir_2', 'dir_3', _dir)
    os.makedirs(path, exist_ok=True)

这就是你需要的。

# do what you want to do

dir_from = os.path.join(DESKTOP_DIR, 'dir_from')
dir_to = os.path.join(DESKTOP_DIR, 'dir_to')
target = '20180828'

for root, dirs, files in os.walk(dir_from, topdown=True):
    for _dir in dirs:
        if _dir == target:
            path = os.path.join(root, _dir).replace(dir_from, dir_to)
            os.makedirs(path, exist_ok=True)
            continue

【讨论】:

  • 因此,您上面提供的代码将在另一个位置创建一个名为 20180828 的文件夹。我要做的是从原始帖子创建整个目录结构,从 dir1 到 dir3,然后只在 dir3 中创建所需的目录,在这种情况下是 20180828。然后我需要进入 20180828 并在其中创建所有目录目录。我的问题是试图忽略 dir3 中除 20180828 之外的所有其他文件夹。我希望我能很好地解释自己。
  • @murphy 啊,我明白了。我编辑了我的答案。我希望它有所帮助。有很多方法可以满足您的需要。这就是其中之一。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-29
  • 2020-11-30
  • 1970-01-01
相关资源
最近更新 更多