我正在编写一个Python脚本,以日期的形式获取用户输入,例如20180829,它将是一个子目录名称,然后使用os.walk函数遍历特定目录,一旦到达传入的目录它将跳入内部并查看其中的所有目录,并在不同的位置创建目录结构。
我的目录结构如下所示:
|dir1
|-----|dir2|
|-----------|dir3
|-----------|20180829
|-----------|20180828
|-----------|20180827
|-----------|20180826
因此dir3将有许多子文件夹,这些子文件夹都将采用日期格式。我需要能够复制仅在开始时传入的目录的目录结构,例如20180829,并跳过目录的其余部分。
我一直在寻找一种方法来做到这一点,但我能找到的是从os.walk函数中排除目录的方法,如下面的主题:qazxsw poi
我还找到了一个线程,允许我打印出我想要的目录路径,但不会让我创建我想要的目录: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
这就是你需要的。
# 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)