Quantcast
Channel: Active questions tagged ubuntu - Stack Overflow
Viewing all articles
Browse latest Browse all 6025

Why is my code using relative paths not working on Ubuntu?

$
0
0

I am trying to read and write files using Python in Visual Studio Code and it is not working properly when I'm on Ubuntu. The path of the script appears to be incorrect to use relative paths.

For example this simple write to a file code:

with open('../out/file_name.txt', 'w') as file:    file.truncate()

I must specify the full path for the file using 'os' library to make it work:

script_directory = os.path.dirname(__file__)out_dir = os.path.join(script_directory, '../out')write_file_path = os.path.join(    out_dir, 'file_name.txt')with open(write_file_path, 'w') as file:    file.truncate()

I do not have this problem when using Windows.

This problem also affects importing classes and methods from other files found in the same work directory.

My project structure is:

  • use-case1
    • agent
      • data
        • txt
      • out
      • src
        • main.py
    • sim

PWD command in the terminal returns /home/user/Documents/Project/Project-Use-Cases/use-case1.


Viewing all articles
Browse latest Browse all 6025

Trending Articles