环境数据

Windows 11
Python3.11.4
VS代码


计划信息

以下是有关我的计划的一些基本信息:
此程序的路径:d:\Learning\Programming\python_work\File_Reader\file_reader.py

file_path = 'File\\pi_digits.txt'
with open(file_path) as file_object:
    contents = file_object.read()
    print(contents)
#This program try to open the file:d:\Learning\Programming\python_work\File_Reader\File\pi_digits.txt
#and print the numbers stored in this file

So both file_reader.py and the folder File are in the folder File_Reader.
pi_digits.txt is in the folder File.
I want to use relative path to tell my program where pi_digits.txt is.
I run the code two times and I think at least my code is correct.


第一次try

我用VS代码在终端中运行它

PS D:\Learning\Programming\python_work\File_Reader> python file_reader.py

结果就是我想要的

3.1415926535
  8979323846
  2643383279

第二次try

我使用Run Code按钮(Crtl+Alt+N)运行它
但它似乎找不到pi_digits.txt在哪里.

[Running] python -u "d:\Learning\Programming\python_work\File_Reader\file_reader.py"
Traceback (most recent call last):
  File "d:\Learning\Programming\python_work\File_Reader\file_reader.py", line 2, in <module>
    with open(file_path) as file_object:
         ^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'File\\pi_digits.txt'

[Done] exited with code=1 in 0.097 seconds

最后一次try

我使用绝对路径重写程序

file_path = 'd:\\Learning\\Programming\\python_work\\File_Reader\\File\\pi_digits.txt'
with open(file_path) as file_object:
    contents = file_object.read()
    print(contents)

上述两种方法都很有效


我不明白为什么当我使用相对路径时,程序在我的第二次try 中不能运行

推荐答案

当您指定相对路径时,重要的是您在运行python file_reader.py时所在的目录.

  1. 当您使用Visual Studio时,它会自动在项目的基目录中加载一个shell .该项目目录还包含文件py_digits.txt,因此一切正常.
  2. 当您使用任何其他终端时,默认情况下,它会在您用户的主目录中加载一个shell .并且该主目录不包含文件py_digits.txt,因此无法找到它.

如果指定绝对路径,则在运行python file_reader.py时位于哪个目录都无关紧要.始终可以找到该文件.

Python-3.x相关问答推荐

数组列的极点成对求和

将数据帧扩展为矩阵索引

没有这样的命令';角色';-可靠分子

Strawberry FastAPI:如何调用正确的函数?

与 pandas 0.22 相比,pandas 2.0.3 中的 df.replace() 会抛出 ValueError 错误

在Pandas中,根据另一列中的重复值将数据分组为一列

为什么不能用格式字符串 '-' 绘制点?

安装没有 sudo 权限的 python3 和 pip3

有效地缩短列表,直到第一次和最后一次出现不同于 None 的值

pymongo 失败并出现错误未定义

在 Python 3.5 中使用 aiohttp 获取多个 url

日志(log)模块不适用于 Python3

Pythonic,自定义警告

Python heapify() 时间复杂度

为什么 2to3 将 mydict.keys() 更改为 list(mydict.keys())?

是否在未完成初始化的对象上调用了 del?

向 Python 函数添加属性的最佳方法

我可以替换 Python 中对象的现有方法吗?

Selenium Python - 处理没有这样的元素异常

Python 3中星型导入的函数形式是什么