[英]Ignore files from specific directory using glob or by os.walk()
I want to exclude the directory 'dir3_txt' so that I can only capture the files('.txt')
from other directory .我想排除目录“dir3_txt”,以便我只能从其他目录捕获
files('.txt')
。 I tried to exclude directory like below but not able to figure it out how to get all the files having .txt as ext other that having it in dir3_txt
using below:我试图排除如下所示的目录,但无法弄清楚如何使用下面的方法将所有具有 .txt 的文件作为 ext 其他在
dir3_txt
中的文件:
for root, dirs, files in os.walk('.'):
print (root)
dirs[:] = [d for d in dirs if not d.startswith('dir3')]
for file in files:
print (os.path.join(root, file))
I am thinking of glob (got below from stack itself) but not sure how to tweak glob to use it.我正在考虑 glob (从堆栈本身下面得到)但不知道如何调整 glob 来使用它。
for file in os.walk('.'):
for txt in glob(os.path.join(files[0], '*.txt')):
print(txt)
I went through Excluding directories in os.walk but the solution provided is not helping me, also it only tells about skipping directory that also is not helpful as I need to get files from other directories , better if we can do it with glob only?我经历了在 os.walk 中排除目录,但提供的解决方案对我没有帮助,它也只告诉我跳过目录也没有帮助,因为我需要从其他目录获取文件,如果我们只能用 glob 来做更好?
A simple solution would just to do a string comparison against the directory-paths and files returned by os.walk
:一个简单的解决方案就是对
os.walk
返回的目录路径和文件进行字符串比较:
for root, dirs, files in os.walk('.'):
if "/dir3_txt/" not in root:
for file in files:
if file.endswith(".txt"):
print (os.path.join(root, file))
for root, dirs, files in os.walk('.'):
print (root)
dirs[:]= [d for d in dirs if d[:4]!='dir3']
for file in files:
if file[-4:]=='.txt':
print (os.path.join(root, file))
I dont have any system with me now to test this , so if any problems please comment.我现在没有任何系统来测试这个,所以如果有任何问题,请发表评论。
Edit:编辑:
Now it only detects '.txt' files.现在它只检测“.txt”文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.