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

折月煮酒 提交于 2019-12-02 03:16:37

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.

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