基于.txt文件的 OS.walk 文件夹排除



我想要一个Folders_To_Skip.txt文件,其中包含用新行分隔的目录列表

前任:

A:\stuffab
A:\junkab

我的文件正在破坏我的.csv记录编译,并且我想排除无论如何我都无法读取的目录。

locate函数中,我有我试图从 os.walk 中的排除目录实现的东西,但我似乎无法让它与list中的目录一起工作,更不用说从文本文件列表中读取时,当我print访问的文件时,它仍然包括我试图排除的目录中的文件。

您能否解释一下解决方案是特定的排除目录(不是世界末日(,还是可以操作排除子目录(会更方便(。

现在,locate前面的代码允许轻松查找控制文本文件,然后将这些项作为列表加载到脚本的其余部分以运行,假设所有控制文件都位于同一位置,但该位置可以根据谁在运行脚本以及从何处更改。

同样出于测试目的Drive_Locations.txt设置为:

A
B

以下是当前脚本:

import os
from tkinter import filedialog
import fnmatch
input('Press Enter to select any file in writing directory or associated control files...')
fname = filedialog.askopenfilename()
fpath = os.path.split(fname)
# Set location for Drive Locations to scan
Disk_Locations = os.path.join(fpath[0], r'Drive_Locations.txt')
# Set location for Folders to ignore such as program files
Ignore = os.path.join(fpath[0], r'Folders_To_Skip.txt')
# Opens list of Drive Locations to be sampled
with open(Disk_Locations, 'r') as Drives:
Drive = Drives.readlines()
Drive = [x.replace('n', '') for x in Drive]
# Iterable list for directories to be excluded
with open(Ignore, 'r') as SkipF1:
Skip_Fld = SkipF1.readlines()
Skip_Fld = [x.replace('n', '') for x in Skip_Fld]
# Locates file in entire file tree from previously established parent directory.
def locate(pattern, root=os.curdir):
for path, dirs, files in os.walk(os.path.abspath(root), topdown=True):
dirs[:] = [d for d in dirs if d not in Skip_Fld]
for filename in fnmatch.filter(files, pattern):
yield os.path.join(path, filename)
for disk in Drive:
# Formats Drive Location for acceptance
disk = str.upper(disk)
if str.find(disk, ':') < 0:
disk = disk + ':'
# Changes the current disk drive
if os.path.exists(disk):
os.chdir(disk)
# If disk incorrect skip to next disk
else:
continue
for exist_csv in locate('*.csv'):
# Skip compiled record output files in search
print(exist_csv)

这里的核心错误是os.walk()返回相对目录名称的列表。所以比如当你在目录A:stuffa中时,你要跳过的目录只是列为b,而不是A:stuffab;因此,当然,您的跳过逻辑不会从当前目录的子目录列表中找到要删除的任何内容。

这是一个重构,它直接检查当前目录。

for path, dirs, files in os.walk(os.path.abspath(root), topdown=True):
if path not in Skip_Fld:
for filename in fnmatch.filter(files, pattern):
yield os.path.join(path, filename)

保持abspath电话很重要;对你把它包含在你的尝试中是件好事。

您要跳过的目录列表应该有一个反斜杠,或者可能是正斜杠,并且可能没有最终的目录分隔符(幸运的是,我没有办法检查 Windows 上的os.walk()是如何报告的(。

最新更新