- How to get an absolute file path in Python
- 11 Answers 11
- Absolute path of a file object
- 2 Answers 2
- How to get an absolute path in Python
- What is an absolute path in Python?
- How to find the absolute path in Python
- Conclusion
- finding out absolute path to a file from python
- 5 Answers 5
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
How to get an absolute file path in Python
Given a path such as «mydir/myfile.txt» , how do I find the file’s absolute path in Python? E.g. on Windows, I might end up with:
"C:/example/cwd/mydir/myfile.txt"
11 Answers 11
>>> import os >>> os.path.abspath("mydir/myfile.txt") 'C:/example/cwd/mydir/myfile.txt'
Also works if it is already an absolute path:
>>> import os >>> os.path.abspath("C:/example/cwd/mydir/myfile.txt") 'C:/example/cwd/mydir/myfile.txt'
Note: On most platforms, this is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)) . So if mydir/myfile.txt do not under os.getcwd() , the absolute path is not the real path.
@coanor ? Without an explicit root, mydir/myfile.txt implicitly refers to a path inside the current working directory as is therefore equivalent to ./mydir/myfile.txt . That might not be the path you intended to input, but it seems like the correct interpretation of the path as far as I can tell. Could you elaborate?
@jpmc26 I don’t exactly follow coanor, but I would say that (contrary to what I presumed), there is no linkage between the argument to the abspath function and a real file. You could give any pathname- non-existent files and directory heirarchies are fine- and abspath will simply resolve the bits of the path (including the parent directory » .. » element) and return a string. This is just a string computed from the current directory; any correlation to an actual file is accidental, it seems. Try os.path.abspath(«/wow/junk/../blha/hooey») . It works.
@MikeS I’m honestly not sure why that would be unexpected behavior. It’s absolute path, not absolute file or directory. If you want an existence check, call os.path.exists . To the contrary, systems like PowerShell that insist on the path existing with the standard path resolution function are a pain to use.
@jpmc26 To assume that a path is just a string that looks like a pathname is not clear at all, and goes counter to how I’ve been thinking and speaking of pathnames for many years. I quote the Python 3 docs for abspath: «Return a normalized absolutized version of the pathname path.» Not a». version of the string path«. A pathname, as defined by Posix, is «A string that is used to identify a file.» The Python docs are explicit about relpath : «the filesystem is not accessed to confirm the existence or nature of path «. If the argument here is obvious, why be explicit for relpath ?
Absolute path of a file object
Instead, I was wondering whether the following is a good solution — basically extending the file class so that on opening, the absolute path of the file is saved:
class File(file): def __init__(self, filename, *args, **kwargs): self.abspath = os.path.abspath(filename) file.__init__(self, filename, *args, **kwargs)
f = File('test','rb') os.chdir('some_directory') f.abspath # absolute path can be accessed like this
An open file descriptor can have multiple links and — thus — multiple absolute path names. You’re doing it backwards. Why aren’t you computing a path first, then opening the file with that absolute path?
2 Answers 2
One significant risk is that, once the file is open, the process is dealing with that file by its file descriptor, not its path. On many operating systems, the file’s path can be changed by some other process (by a mv operation in an unrelated process, say) and the file descriptor is still valid and refers to the same file.
I often take advantage of this by, for example, beginning a download of a large file, then realising the destination file isn’t where I want it to be, and hopping to a separate shell and moving it to the right location – while the download continues uninterrupted.
So it is a bad idea to depend on the path remaining the same for the life of the process, when there’s no such guarantee given by the operating system.
It depends on what you need it for.
As long as you understand the limitations—someone might move, rename, or hard-link the file in the interim—there are plenty of appropriate uses for this. You may want to delete the file when you’re done with it or if something goes wrong while writing it (eg. gcc does this when writing files):
f = File(path, "w+") try: . except: try: os.unlink(f.abspath) except OSError: # nothing we can do if this fails pass raise
If you just want to be able to identify the file in user messages, there’s already file.name. It’s impossible to use this (reliably) for anything else, unfortunately; there’s no way to distinguish between a filename » » and sys.stdin, for example.
(You really shouldn’t have to derive from a builtin class just to add attributes to it; that’s just an ugly inconsistent quirk of Python. )
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.
finding out absolute path to a file from python
If I have a file test.py that resides in some directory, how can I find out from test.py what directory it is in? os.path.curdir will give the current directory but not the directory where the file lives. If I invoke test.py from some directory foo , os.curdir will return foo but not the path of test.py . thanks.
5 Answers 5
Here’s how to get the directory of the current file:
import os os.path.abspath(os.path.dirname(__file__))
which returns a relative path.
can be used to get the full path.
The answers so far have correctly pointed you to os.path.abspath , which does exactly the job you requested. However don’t forget that os.path.normpath and os.path.realpath can also be very useful in this kind of tasks (to normalize representation, and remove symbolic links, respectively) in many cases (whether your specific use case falls among these «many» is impossible to tell from the scant info we have, of course;-).
import os dirname, filename = os.path.split(os.path.abspath(__file__))
os.path has lots of tools for dealing with paths and getting information about paths.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.