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

Blake Stone picture Blake Stone · Apr 7, 2016 · Viewed 7.2k times · Source

First of all, I'm very new to Python and programming in general.

Currently I'm trying to create a script that will remove all files with random names, extensions and content in the folder according to the lines from the blacklist (search must be done in the files' content).

Here is a 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)

I'm getting this error:

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

Could you help me please?

Thanks in advance!

Answer

aluriak picture aluriak · Apr 7, 2016

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.