How to resolve relative paths in python?

I have a directory structure like this

projectfolder/fold1/fold2/fold3/script.py 

now I give the script.py path as a command line argument to the file that is in

 fold1/fold_temp/myfile.txt 

So basically I want you to have a path this way

 ../../fold_temp/myfile.txt >>python somepath/pythonfile.py -input ../../fold_temp/myfile.txt 

The problem here is that I can be given the full path or relative path so that I can solve and based on this I would have to create an absolute path.

I already have knowledge of the functions associated with the path.

Question 1

Question 2

Help questions give a partial answer, but I don’t know how to build a full path using the functions provided in them.

+11
source share
4 answers
 import os dir = os.path.dirname(__file__) path = raw_input() if os.path.isabs(path): print "input path is absolute" else: path = os.path.join(dir, path) print "absolute path is %s" % path 

Use os.path.isabs to judge if the input path is absolute or relative, if it is relative, and then use os.path.join to convert it to absolute

-2
source

try os.path.abspath , it should do what you want;)

In fact, it converts any given path into an absolute path with which you can work, so you do not need to distinguish between relative and absolute paths, just normalize any of them using this function.

Example:

 from os.path import abspath filename = abspath('../../fold_temp/myfile.txt') print(filename) 

It will print the absolute path to your file.

EDIT:

If you are using Python 3.4 or later, you can also use the resol () method of pathlib.Path . Keep in mind that this will return a Path object, not a string. If you need a string, you can still use str() to convert it to a string.

Example:

 from pathlib import Path filename = Path('../../fold_temp/myfile.txt').resolve() print(filename) 
+26
source

For Python3, you can use the pathlib resolve function to remove symbolic links and .. components.

You should have a Path object, but it is very simple to do the conversion between str and Path.

I recommend anyone using Python3 to drop os.path and its messy names of long functions and bind to pathlib Path objects.

+2
source

Practical example:

sys.argv[0] name of the current script

os.path.dirname() gives you the relative directory name

thus, the following line gives you the absolute working directory of the current executable.

cwd = os.path.abspath(os.path.dirname(sys.argv[0]))

Personally, I always use this instead of os.getcwd() since it gives me the absolute path to the script, regardless of the directory from which the script was called.

0
source

All Articles