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

使用os模块创建目录内文件失败,os.path.exists返回False

问题分析与解决办法
  • 你提供的代码仅完成了路径拼接和文件存在性检查,完全没有包含创建文件的逻辑,所以文件不存在、os.path.exists()返回False是符合预期的结果。
  • 要在指定路径创建first.txt文件,需要添加文件创建的代码,示例如下:
    import os
    
    cur_directory = os.getcwd()
    file1 = 'first.txt'
    combined = os.path.join(cur_directory, file1)
    
    # 新增创建文件的逻辑:用with语句自动管理文件句柄
    with open(combined, 'w') as f:
        # 若只需创建空文件,用pass即可;如需写入内容,可添加f.write("内容")
        pass
    
    print(combined)
    print(os.path.exists(combined))  # 此时会返回True
    
  • 额外说明:
    • open()函数的'w'模式:文件不存在时创建,存在则清空原有内容
    • 若需保留文件原有内容并追加写入,可使用'a'模式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:52:38