Home > front end >  File not found error altough file does not exist
File not found error altough file does not exist

Time:03-18

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.

CodePudding user response:

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.

CodePudding user response:

You can join paths e.g. with:

filepath = '/'.join((basepath, path_to_specific_file))

Or do as Kris suggested: use pathlib:

>>> basepath = Path('/tmp/')
>>> path_to_specific_file = Path('test')
>>> filepath = basepath / path_to_specific_file
>>> print(filepath)
/tmp/test

EDIT:

To access $HOME (~) you can use Path.home().

  • Related