Passing a file location to python
Rather than hardcoding paths in your Python script we should make use of the path operation from the module os.
os.path.expanduser(path) expands the path to the user’s home directory
os.path.join(path1,*path2*. ) joins path elements with the appropriate separator
os.sep gives the OS dependent path separator ( / for Linux/Unix, \ for Windows)
os.getcwd() gives the current working directory
os.path.abspath(path) gives the OS dependent absolute path of a given path
>>>import os >>>path = os.path.join(os.path.expanduser('~'), 'documents', 'python', 'file.txt') >>>print (path)
/home/user/documents/python/file.txt ## when on Ubuntu C:\Users\user\documents\python\file.txt ## when running Windows
I don’t have permission to add comments. so I will just try to answer.
The path at UNIX will be like: /home/user/file.txt
When you at any folder and want to get the absolute path of a file, you could use the readlink command:
$ readlink -f format.log /home/dli/format.log
File paths are written as-
Everything in your home folder is located inside /home/username/
So, if you have a file on your desktop, it is located in /home/username/Desktop/
Other partitions are mounted in /media by default.
If you directly want to get the path of a file, you can copy the file, and paste it into your text editor, this should give you the path to your file. Put a \ before every space in the path to ‘escape’ the space. e.g. /media/myuseraccount/Desktop/an awesome file would be written as:
/media/myuseraccount/Desktop/an\ awesome\ file
Another thing to note is that in Linux, your file names are case sensitive, so ‘desktop’ is not the same as ‘Desktop’.
Finally, a shortcut to your home folder is to type ~
So, you can access your desktop by typing:
and you can access your home folder by typing:
How to get an absolute path in Python
Operating systems such as Windows, Linux, or macOS have different path structures in which operating system files are stored.
Therefore when you run Python scripts on these machines and want to fetch files or directories, you want to find the file’s absolute path relative to the current directory automatically instead of hardcoding it for every system.
An absolute path is also known as the full path and starts with / in Linux and macOS and C:/ on Windows.
To find an absolute path in Python you import the os module then you can find the current working directory using os.path.abspath(«insert-file-name-here») in your Python script.
What is an absolute path in Python?
An absolute path in Python is the full path starting from the root of the operating file system up until the working directory.
So let’s say you run your Python code in /Users/dannysteenman/home/projects/example-project/app.py . This is the entry point where you run the top-level code of your python module.
Then this is the absolute path of your working directory /Users/dannysteenman/home/projects/example-project/ .
How to find the absolute path in Python
As mentioned at the beginning of this article you can run your Python app on different operating systems, therefore you want to automatically find the full path of the file you wish to import in your code instead of hardcoding it.
So given a path such as «src/examplefile.txt» , how do you find the file’s absolute path relative to the current working directory ( /Users/dannysteenman/home/projects/example-project/ ) in Python?
To get the absolute path in Python you write the following code:
import os os.path.abspath("src/examplefile.txt")
To explain the Python code: first, you have to import the os module in Python so you can run operating system functionalities in your code.
Then you use the os.path library to return a normalized absolutized version of the pathname path.
This will result in the following output:
/Users/dannysteenman/home/projects/example-project/src/examplefile.txt
Conclusion
As you can see an absolute path helps you find the full path of a file or directory relative to the current working directory. This is useful since you get the flexibility to find files or folders and return the correct path on different operating systems.
To get an absolute path in Python you use the os.path.abspath library. Insert your file name and it will return the full path relative from the working directory including the file.
If you need guidance on finding a relative path in Python, read the following article below.
How do you get the absolute path of a file in Python?
I have read quite a few links on the site saying to use «os.path.abspath(#filename)». This method isn’t exactly working for me. I am writing a program that will be able to search a given directory for files with certain extensions, save the name and absolute path as keys and values (respectively) into a dictionary, and then use the absolute path to open the files and make the edits that are required. The problem I am having is that when I use os.path.abspath() it isn’t returning the full path. Let’s say my program is on the desktop. I have a file stored at «C:\Users\Travis\Desktop\Test1\Test1A\test.c». My program can easily locate this file, but when I use os.path.abspath() it returns «C:\Users\Travis\Desktop\test.c» which is the absolute path of where my source code is stored, but not the file I was searching for. My exact code is:
import os Files=<>#Dictionary that will hold file names and absolute paths root=os.getcwd()#Finds starting point for root, dirs, files in os.walk(root): for file in files: if file.endswith('.c'):#Look for files that end in .c Files[file]=os.path.abspath(file)
os.path encourages lots of error-prone patterns in your code. You should probably avoid it as much as you can. Consider one of the better third-party path libraries (something like pypi.python.org/pypi/filepath or even pypi.python.org/pypi/strpath)
@Jean-PaulCalderone: That’s nonsense. People don’t always understand what is relative and what is absolute, but to claim that os.path encourages lots of error-prone patterns is ludicrous.
@Jean-PaulCalderone: and if you want to recommend a OO approach to path handling, why not pathlib ? As of Python 3.4, that’s now part of the standard lib.
constructing absolute path with os.path.join()
I’d like to construct an absolute path in python, while at the same time staying fairly oblivious of things like path-separator. edit0: for instance there is a directory on the root of my filesystem /etc/init.d (or C:\etc\init.d on w32), and I want to construct this only from the elements etc and init.d (on w32, I probably also need a disk-ID, like C: ) In order to not having to worry about path-separators, os.join.path() is obviously the tool of choice. But it seems that this will only ever create relative paths:
print("MYPATH: %s" % (os.path.join('etc', 'init.d'),) MYPATH: etc/init.d
print("MYPATH: %s" % (os.path.join('', 'etc', 'init.d'),) MYPATH: etc/init.d
Making the first element absolute obviously helps, but this kind of defeats the idea of using os.path.join()
print("MYPATH: %s" % (os.path.join('/etc', 'init.d'),) MYPATH: /etc/init.d
edit1: using os.path.abspath() will only try to convert a relative path into an absolute path. e.g. consider running the following in the working directory /home/foo :
print("MYPATH: %s" % (os.path.abspath(os.path.join('etc', 'init.d')),) MYPATH: /home/foo/etc/init.d
edit2: the question really boils down to: since the leading slash in /etc/init.d makes this path an absolute path, is there a way to construct this leading slash programmatically? (I do not want to make assumptions that a leading slash indicates an absolute path)