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

os.path.exists()脚本返回False但IDLE返回True,如何修复?

问题解决思路

核心原因是脚本运行时的工作目录和IDLE的工作目录不一致。IDLE默认把testfolder作为工作目录,所以能找到file.txt;但你运行test.py时,可能是从其他路径启动的,导致相对路径file.txt指向的不是testfolder里的目标文件。

解决方案:使用绝对路径定位文件

修改代码,通过__file__获取当前脚本的绝对路径,再拼接目标文件的路径,这样不管从哪里运行脚本,都能准确找到file.txt:

import requests
from os.path import exists, abspath, dirname, join

def downloadfile(url):
    # 获取脚本所在目录的绝对路径
    script_dir = dirname(abspath(__file__))
    # 拼接file.txt的绝对路径
    file_path = join(script_dir, 'file.txt')
    
    if not exists(file_path):
        local_filename = url.split('/')[-1]
        # 把下载的文件也保存到脚本所在目录
        save_path = join(script_dir, local_filename)
        with requests.get(url, stream=True) as r:
            r.raise_for_status()
            with open(save_path, 'wb') as f:
                for chunk in r.iter_content(chunk_size=8192):
                    f.write(chunk)
    return

downloadfile('https://url.to/file.txt')

额外验证方法

你可以在脚本里先打印当前工作目录,确认问题根源:

import os
print(os.getcwd())

运行脚本后,对比这个路径和testfolder的实际路径,就能直观理解为什么找不到文件了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 17:15:58