循环遍历目录中的文件时如何得到此错误? “ OSError:[Errno 2]没有这样的文件或目录”

问题描述 投票:0回答:1

我需要在目录中删除数千个文件。我要保留前十个(按字母/数字顺序)与条件匹配的内容。例如,我要保留“文件名部分abc00000.filetype”,而不是“文件名部分abc42422.filetype”。以下是我用来执行此操作的代码:

import os


i = 0
for f in os.listdir('/dir/dir'):
    if 'part-of-file-name' in f:
        i = i + 1
        if i > 10:
            os.remove(f)
    else:
        os.remove(f)
print("Files found: " + str(i))
print("Files removed: " + str(i - 10))

这是我得到的错误:

OSError: [Errno 2] No such file or directory: 'part-of-file-name-i-want-then-other-parts.filetype'

这对我来说毫无意义。该文件显然存在;否则,我不会读取错误中的整个文件名。

python python-2.6
1个回答
0
投票

检出您的路径目录

os.listdir('./dir/dir')

如果目录在您运行的脚本文件中。您可以通过

检查我们的路径是否存在
import os
path = './dir/dir'
print(os.path.exists(path))

# True
# Means the path exists if its false means you are directing the path to a false location
© www.soinside.com 2019 - 2024. All rights reserved.