How am I getting this error when looping through files in a directory? "OSError: [Errno 2] No such file or directory"

How am I getting this error when looping through files in a directory? "OSError: [Errno 2] No such file or directory"

我在一个目录中有数千个文件需要删除。我想保留符合条件的前十个 (alphabetically/numerically)。例如,我想保留 'part-of-file-name-abc00000.filetype' 而不是 'part-of-file-name-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))

这是我遇到的错误:

File "delete_data_files.py", line 11, in <module>
    os.remove(f)
OSError: [Errno 2] No such file or directory: 'part-of-file-name-i-want-then-other-parts.filetype'

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

检查你的路径目录

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
import os
i = 0
path = './dir/dir'
for f in os.listdir(path):
    print "file path", f
    f = path + "/" + f;
    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))

输出: 文件路径部分文件-name.txt

找到的文件:1

删除的文件:-9

您只提供了文件名。您需要提供删除文件的完整路径。