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

Python中pathlib硬编码路径正常,改为用户输入后扫描失败求助

解决Python输入文件夹路径后扫描文件出错的问题

以下是几个常见问题及修复方案:

  • 遍历到子文件夹导致报错
    folder.iterdir()会返回目标文件夹下的所有条目(包括子文件夹),用open()尝试打开文件夹必然失败。只需添加判断,只处理文件:

    for path in folder.iterdir():
        if path.is_file():  # 过滤掉子文件夹
            with open(path, encoding='utf-8') as file:
                text = file.read().lower()
    
  • 输入路径含多余引号或格式错误
    用户输入路径时可能不小心带上引号(比如从资源管理器复制的"C:\Test"),导致路径无效。可以先去除输入两端的引号:

    input_path = input("What folder do you want to scan? : ").strip('"')
    folder = pathlib.Path(input_path)
    
  • 未处理文件读取异常
    部分文件可能是二进制格式、编码非UTF-8,或者没有读取权限,直接读取会触发错误。添加异常处理跳过这类文件:

    for path in folder.iterdir():
        if path.is_file():
            try:
                with open(path, encoding='utf-8') as file:
                    text = file.read().lower()
                # 在这里添加你的高频词统计逻辑
            except UnicodeDecodeError:
                print(f"跳过无法解码的文件: {path}")
            except PermissionError:
                print(f"无权限读取文件: {path}")
    
  • 路径不存在或不是文件夹
    先验证输入路径的有效性,避免后续操作报错:

    input_path = input("What folder do you want to scan? : ").strip('"')
    folder = pathlib.Path(input_path)
    if not folder.exists() or not folder.is_dir():
        print("输入的路径不存在或不是有效文件夹,请重新输入")
        exit()
    

另外,推荐使用with语句打开文件,它会自动关闭文件句柄,避免资源泄漏,比直接open()后手动关闭更安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 04:33:34