环境数据
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 中不能运行