Search code examples
python-3.xlinuxfile-not-found

File not found error altough file does not exist


I am trying to read through a file using the with open () function from python. I hand in the filepath via a base path and then a relative path adding on it:

filepath = base_path + path_to_specific_file

with open (filepath) as l:
    do_stuff()

base_path is using the linux home symbol ( I am using Ubuntu on a VM) ~/base_path/ since I want to have the filepath adapted on every device instead of hardcoding it.

This does not work. When I execute the code, it throws a file not found error, although the path exists. I even can open it by clicking the path in the vscode terminal.

According to this thread:

File not found from Python although file exists

the problem is the ~/ instead of /home/username/. Is there a way to replace this to have it working on every device with the correct path? I cannot comment yet on this thread since I do not have enough reputation, therefore I needed to create this new question. Sorry about that.


Solution

  • You can use the expanduser() from pathlib for this. Example

    import pathlib
    filepath = pathlib.Path(base_path) / path_to_specific_file
    filepath = filepath.expanduser() # expand ~
    
    with open(filepath) as l:
        do_stuff()
    

    This should work fine.