Python - 打印除一个目录外的所有目录
Python - Print all the directories except one
我有一个 python 脚本可以打印主目录中的所有目录。我想要的是打印除旧目录(我包含在排除列表中)之外的所有目录。
为此,我使用以下脚本:
include = 'C://Data//'
exclude = ['C:/Data//00_Old']
for root, dirs, files in os.walk(include, topdown=False):
dirs[:] = [d for d in dirs if d not in exclude]
for name in dirs:
directory = os.path.join(root, name)
print(directory)
问题是:它正在打印所有目录,包括被排除的目录。我做错了什么?
文件系统相关需求最好使用pathlib
模块。我建议尝试这样的事情。
from pathlib import Path
files = list(Path('C:/Data/').glob('**/*')) #recursively get all the file names
print([x for x in files if 'C:/Data/00_Old' not in str(x)])
要进一步简化它,您可以这样做:
from pathlib import Path
# I'm assuming this is where all your sub-folders are that you want to filter.
include = 'C://Data//'
# You don't need the parent 'C://Data//' because you looping through the parent folder.
exclude = ['00_Old']
root_folder = Path(include)
for folder in root_folder.iterdir():
if folder not in exclude:
# do work
我有一个 python 脚本可以打印主目录中的所有目录。我想要的是打印除旧目录(我包含在排除列表中)之外的所有目录。
为此,我使用以下脚本:
include = 'C://Data//'
exclude = ['C:/Data//00_Old']
for root, dirs, files in os.walk(include, topdown=False):
dirs[:] = [d for d in dirs if d not in exclude]
for name in dirs:
directory = os.path.join(root, name)
print(directory)
问题是:它正在打印所有目录,包括被排除的目录。我做错了什么?
文件系统相关需求最好使用pathlib
模块。我建议尝试这样的事情。
from pathlib import Path
files = list(Path('C:/Data/').glob('**/*')) #recursively get all the file names
print([x for x in files if 'C:/Data/00_Old' not in str(x)])
要进一步简化它,您可以这样做:
from pathlib import Path
# I'm assuming this is where all your sub-folders are that you want to filter.
include = 'C://Data//'
# You don't need the parent 'C://Data//' because you looping through the parent folder.
exclude = ['00_Old']
root_folder = Path(include)
for folder in root_folder.iterdir():
if folder not in exclude:
# do work