Search code examples
pythonioerror

Python on Windows: IOError: [Errno 2] No such file or directory


I'm trying to remove all files from a folder which contan certain "blacklisted" content. I have this code:

import os

black_list = [line for line in open("C:/path/to/blacklist.txt")]

for filename in os.listdir("C:/path/to/files/"):
    content = open(filename).read()
    if any(line in content for line in black_list):
        os.remove(filename)

But I get an error like:

IOError: [Errno 2] No such file or directory: 'first_file_from_the_folder'

Why does this happen?


Solution

  • os.listdir returns filenames, not complete path.

    PATH = "C:/path/to/files/"
    for filename in os.listdir(PATH):
        content = open(os.path.join(PATH, filename)).read()
    

    Here, os.path.join is used for merge the path and the filename.