anon
anon

Reputation: 866

Problems while getting relative paths of a file?

I am reading in a different machine a file. Therefore, I need to access to the full path of the file. So I tried to use pythons Pathlib module:

a_path = '/dir1/subdir1/sample.txt'
home = str(Path.home())
a_path = str(home) + str(a_path)

Apparently, the above code return me the full path. However, when I read it I get:

FileNotFoundError: [Errno 2] No such file or directory: "/home/user'/dir1/subdir1/sample.txt'"

How can I fix the above error? maybe in the concatenation I am getting problems.

Upvotes: 0

Views: 135

Answers (3)

F. Pareto
F. Pareto

Reputation: 334

First of all, '/dir1/subdir1/sample.txt' is an absolute path. If you want it to be a relative path (which seems to be the case) you should use 'dir1/subdir1/sample.txt', so without a leading /.

Using the pathlib library this then becomes very easy

>>> from pathlib import Path
>>> a_path = "dir1/subdir1/sample.txt"
>>> a_path = Path.home() / a_path
>>> print(a_path)
/home/pareto/dir1/subdir1/sample.txt

Again, make sure you are not using absolute paths. Otherwise you would get the following

>>> print(Path.home() / "/dir1/subdir1/sample.txt")
/dir1/subdir1/sample.txt

Upvotes: 0

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

Try this. This uses os.path.join which joins two paths together

import os
import pathlib
a_path = 'dir1/subdir1/sample.txt'
home = str(pathlib.Path.home())
print(os.path.join(home, a_path))
#/home/user/dir1/subdir1/sample.txt

Upvotes: 1

Slayer
Slayer

Reputation: 882

You can use join to paste the string together.

''.join([str(Path.home()), 'path\\t.txt'])

Upvotes: 0

Related Questions