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

我只是一个虾纸丫 提交于 2019-12-02 05:57:33

问题


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!


回答1:


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.




回答2:


if you want to remove the file, it should pass the whole path of file.

import os

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


来源:https://stackoverflow.com/questions/36477665/python-on-windows-ioerror-errno-2-no-such-file-or-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!