简体   繁体   中英

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

I have thousands of files I need to delete in a directory. I want to keep the first ten (alphabetically/numerically) that match the conditions. For example, I want to keep 'part-of-file-name-abc00000.filetype' but not 'part-of-file-name-abc42422.filetype'. Below is the code I'm using to do so:

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))

This is the error I'm getting:

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'

This makes no sense to me. The file obviously exists; otherwise, I would not be reading the entire file name in the error.

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))

Output: file path part-of-file-name.txt

Files found: 1

Files removed: -9

You are providing file name only. You need to provide full path for removing the files.

check out for your path directory

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

if the directories are in the script file you run. You can check our wether the path exists by

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM