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

标签 python ioerror

首先,我对 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/

相关文章:

python - PyInstaller 但保持 .py 文件可升级

Python IOError.strerror 不是 Unicode

python - 崩溃后Python脚本无法重新启动

python - 在 Pandas 的 GroupBy 中检查负滚动窗口中的条件

python - 我正在尝试获取所选列表项的索引值

python - 如何在 CentOS 中安装 jdbc 并在 python 函数中使用包?

android - 文件未找到异常 :/storage/emulated/0/Android

python - 无法在 python 中打开图像文件

java - FileUtils.copyFile 对大文件失败

python - 在列表中查找项目时不应该出现 Elif 语句