skip to Main Content

Environment Data

Windows 11
python 3.11.4
VS Code


Program Information

Here is some basic information about my program:
This program`s path: d:LearningProgrammingpython_workFile_Readerfile_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:LearningProgrammingpython_workFile_ReaderFilepi_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.


First Try

I run it in the terminal in VS Code

PS D:LearningProgrammingpython_workFile_Reader> python file_reader.py

And the result is exactly what I want

3.1415926535
  8979323846
  2643383279

Second Try

I run it using the Run Code button(Crtl+Alt+N)
But it seems that it fails to find where pi_digits.txt is.

[Running] python -u "d:LearningProgrammingpython_workFile_Readerfile_reader.py"
Traceback (most recent call last):
  File "d:LearningProgrammingpython_workFile_Readerfile_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

The Last Try

I rewrite the program using the absolute path

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)

Both methods above work well


I cannot figure out why when I use relative path, the program doesn`t work in my Second Try

2

Answers


  1. When you specify a relative path, it matters which directory you are in when running python file_reader.py.

    1. When you use Visual Studio, it will automatically load a shell in the project’s base directory. That project directory also contains the file py_digits.txt, so everything works fine.
    2. When you use any other terminal, it will by default load a shell in your user’s home directory. And that home directory does not contain a file py_digits.txt, so it cannot be found.

    When you specify an absolute path, it does not matter which directory you are in when running python file_reader.py. The file can always be found.

    Login or Signup to reply.
  2. As was mentioned by jraufeisen, this is to do with the different paths from vscode and the terminal.

    I therefore tend to do something like this to have general code, but an unambiguous path.

    import os
    
    current_file = os.path.abspath(__file__)
    print(current_file)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search