首先,我对 Python 和一般编程还很陌生。
目前我正在尝试创建一个脚本,该脚本将根据黑名单中的行删除文件夹中所有具有随机名称、扩展名和内容的文件(必须在文件内容中进行搜索)。
代码如下:
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)
我收到这个错误:
IOError: [Errno 2] No such file or directory: 'first_file_from_the_folder'
你能帮帮我吗?
提前致谢!
最佳答案
os.listdir
返回文件名,而不是完整路径。
PATH = "C:/path/to/files/"
for filename in os.listdir(PATH):
content = open(os.path.join(PATH, filename)).read()
这里,os.path.join
用于合并路径和文件名。
关于Windows 上的 Python : IOError: [Errno 2] No such file or directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36477665/