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
- data
- sim
- agent
PWD command in the terminal returns /home/user/Documents/Project/Project-Use-Cases/use-case1.