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

Python用相对路径创建文件报[Errno 2]错误的问题求助

Python创建文件报FileNotFoundError的原因及解决方法

运行Python脚本时,尝试用相对路径创建文件失败,报错如下:

Traceback (most recent call last):
  File "c:\Users\*\Documents\GitHub\_Testes\novo_teste.py", line 1, in <module>
    teste = open('teste.txt', 'w')
            ^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'teste.txt'

已尝试'w'、'w+'、'x'、'x+'模式,仅使用脚本所在目录的绝对路径时有效。原以为相对路径会基于脚本目录,但实际并非如此。

随后尝试用os.getcwd()拼接路径:

import os
print(os.getcwd())  # Show the actual directory
arquivo = open(os.getcwd()+"\\teste.txt", "w")
arquivo.write('teste')
arquivo.close()

执行结果:

PS C:\Users\*\Documents\GitHub\_Testes> & C:/Users/*/AppData/Local/Programs/Python/Python311/python.exe c:/_Projetos/_Testes/testes.py
C:\Users\*\Documents\GitHub\_Testes
Traceback (most recent call last):
  File "c:\_Projetos\_Testes\testes.py", line 3, in <module>
    arquivo = open(os.getcwd()+"\\teste.txt", "w")
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\*\Documents\GitHub\_Testes\teste.txt'

原因分析

  1. 当前工作目录≠脚本所在目录:从执行命令能看到,你是在C:\Users\*\Documents\GitHub\_Testes目录下运行位于c:/_Projetos/_Testes/的脚本,os.getcwd()返回的是执行命令时的当前工作目录,而非脚本本身所在的目录。
  2. 相对路径基准错误:Python中相对路径的基准是当前工作目录,不是脚本所在目录,这是你误以为相对路径会基于脚本目录的核心误区。
  3. 目录权限或存在性问题:报错显示无法找到目标路径,要么是该目录实际不存在(虽在该目录下执行命令,但可能存在路径拼写错误或目录被删除),要么是你的账号没有该目录的写入权限。

解决方法

方法1:获取脚本所在目录并拼接路径(推荐)

使用os.path或pathlib模块获取脚本的绝对路径,确保文件创建在脚本所在目录:

# 使用os.path模块
import os
# 获取脚本所在目录
script_dir = os.path.dirname(os.path.abspath(__file__))
# 拼接文件路径(自动处理系统路径分隔符)
file_path = os.path.join(script_dir, "teste.txt")
# 用with语句自动管理文件关闭
with open(file_path, "w") as arquivo:
    arquivo.write('teste')

或者用更简洁的pathlib(Python 3.4+):

from pathlib import Path
# 获取脚本所在目录的绝对路径
script_dir = Path(__file__).parent.resolve()
# 拼接文件路径(支持路径运算符)
file_path = script_dir / "teste.txt"
with open(file_path, "w") as arquivo:
    arquivo.write('teste')

方法2:切换当前工作目录到脚本目录

先切换工作目录到脚本所在路径,再使用相对路径:

import os
# 获取脚本所在目录
script_dir = os.path.dirname(os.path.abspath(__file__))
# 切换工作目录
os.chdir(script_dir)
# 此时相对路径基于脚本目录
with open("teste.txt", "w") as arquivo:
    arquivo.write('teste')

方法3:检查目标目录的权限与存在性

如果确实要在os.getcwd()返回的目录创建文件,先确认目录状态:

import os
cwd = os.getcwd()
# 检查目录是否存在,不存在则创建
if not os.path.exists(cwd):
    os.makedirs(cwd)
# 拼接路径并创建文件
file_path = os.path.join(cwd, "teste.txt")
with open(file_path, "w") as arquivo:
    arquivo.write('teste')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:30:16