You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用os.listdir遍历文件夹时触发FileNotFoundError的排查求助

问题:遍历指定文件夹文件时出现FileNotFoundError

我正在为课程开发一款恶意软件分类器,逻辑是先用良性软件(goodware)和恶意软件(malware)样本训练模型,再用未知文件集测试,基于特定特征完成分类并输出未知文件标签。现在卡在遍历指定文件夹的循环上——用os.listdir()配合命令行参数指定目标文件夹,但试了数小时都没解决。我已经尝试过绝对路径和相对路径作为命令行参数,还怀疑过子文件夹权限问题,但都没用。

命令行执行语句

python3 PEexample.py gw/ mw/ unknown/

完整报错信息

Traceback (most recent call last):
  File "/Users/kyleefriederichs/Desktop/School/CSCE_698_CyberDefense/CSCE689_CyberDefense/Cyber_practice/PEexample.py", line 39, in <module>
    pe1 = pefile.PE(file)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pefile.py", line 2895, in __init__
    self.__parse__(name, data, fast_load)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pefile.py", line 2970, in __parse__
    stat = os.stat(fname)
FileNotFoundError: [Errno 2] No such file or directory: 'gw1.exe'

相关代码片段

idx_gw = 0
for file in os.listdir(sys.argv[1]):
    # pe1=pefile.PE(file)
    if not file.startswith("."):
        try:
            pe1 = pefile.PE(file)
        except pefile.PEFormatError:
            sys.exit("[-] Not PE file:" + file)

        pe_gw_imps = len(pe1.DIRECTORY_ENTRY_IMPORT)
        idx_gw += 1

问题原因

os.listdir()返回的只是文件夹内的文件名,不是完整路径。当你直接用pefile.PE(file)时,Python会在当前工作目录下查找该文件,而非你指定的sys.argv[1]文件夹,因此找不到文件并抛出FileNotFoundError。

修复方法

需要将命令行传入的文件夹路径与文件名拼接成完整路径,推荐用os.path.join()处理(自动适配不同系统的路径分隔符):

修改后的代码:

import os
import sys
import pefile

idx_gw = 0
# 获取目标文件夹路径
target_dir = sys.argv[1]
for file in os.listdir(target_dir):
    if not file.startswith("."):
        # 拼接完整文件路径
        full_path = os.path.join(target_dir, file)
        try:
            pe1 = pefile.PE(full_path)
        except pefile.PEFormatError:
            print(f"[-] Not PE file: {full_path}")
            continue  # 跳过非PE文件,继续处理其他文件
        except FileNotFoundError:
            print(f"[-] File not found: {full_path}")
            continue

        pe_gw_imps = len(pe1.DIRECTORY_ENTRY_IMPORT)
        idx_gw += 1

额外优化点

  • 避免用sys.exit()直接终止程序,遇到非PE文件时跳过即可,保证后续文件能正常处理
  • 新增FileNotFoundError捕获,避免意外情况导致程序崩溃

内容的提问来源于stack exchange,提问作者Vyxxen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 18:30:35