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

使用Argparse时触发目录未找到错误,无Argparse时代码运行正常

报错原因
  • os.mkdir() 仅支持创建单级目录,你要创建的路径../fileorganizer/files/docs中,如果上级路径../fileorganizer/files本身不存在,os.mkdir()无法自动创建缺失的上级目录,就会触发FileNotFoundError。
  • 你使用的相对路径基准是执行脚本时的终端工作目录,而非脚本文件本身的存储目录。接入argparse前后你可能在不同目录执行脚本,导致相对路径解析结果和预期不一致。
修复代码
import os
import argparse

def crea_cartella(nomeCartella, directory):
    newDirectory = os.path.join(directory, nomeCartella)
    # 替换os.mkdir为os.makedirs,支持创建多级目录,exist_ok=True避免目录已存在时报错
    os.makedirs(newDirectory, exist_ok=True)

def main():
    parser = argparse.ArgumentParser(description="sposta un file nella cartella di destinazione")
    parser.add_argument("--nomeFile", type=str, help="nome file compreso di estensione")
    args = parser.parse_args()
    # 改为基于脚本本身位置的绝对路径,避免执行目录不同导致路径错误
    script_root = os.path.dirname(os.path.abspath(__file__))
    directory = os.path.join(script_root, "files")
    crea_cartella("docs", directory)

if __name__ == '__main__':
    main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 02:24:02