pathlib is the more modern way since Python 3.4. The documentation for pathlib says that "For low-level path manipulation on strings, you can also use the os.path module."
It doesn't make much difference for joining paths, but other path commands are more convenient with pathlib compared to os.path. For example, to get the "stem" (filename without extension):
os.path: splitext(basename(path))[0]
pathlib: path.stem
Also, you can use the same type of syntax (commas instead of slashes) to join paths with pathlib as well:
path_2 = Path("/home", "test", "test.txt")
pathlib is the more modern way since Python 3.4. The documentation for pathlib says that "For low-level path manipulation on strings, you can also use the os.path module."
It doesn't make much difference for joining paths, but other path commands are more convenient with pathlib compared to os.path. For example, to get the "stem" (filename without extension):
os.path: splitext(basename(path))[0]
pathlib: path.stem
Also, you can use the same type of syntax (commas instead of slashes) to join paths with pathlib as well:
path_2 = Path("/home", "test", "test.txt")
os.path is string-based while pathlib is object oriented
os.path operates on strings while pathlib is object-oriented (the documentation at this link speaks about Object-oriented filesystem paths). So if "/home/test/test.txt" is the absolute path (in POSIX format) to access to the file test.txt in the directory /home/test/, the instructions:
from os import path
path_1 = path.join("/home", "test", "test.txt")
(executed in a Linux system) return in path_1, the string "/home/test/test.txt" (link to os.path.join() documentation.)
On the other hand, the following commands:
from pathlib import Path
path_2 = Path("/home") / "test" / "test.txt"
return an object called path_2 which represents the file.
A function and a method available with the 2 approaches
By the previous initialization, essentially:
The string
path_1can be used as argument of other functions of the moduleos.path. For example, to check if a file exists:from os import path if path.exists(path_1): # the file exists do stuffThe object
path_2is an instance of the classpathlib.Path, so with this object it is possible to call all methods of the classPath.Furthermore, if
path_2is created on a POSIX compliant system (such as Linux), its type isPosixPath(a subclass ofPath), else ifpath_2is created on a Windows system, its type isWindowsPath(a subclass of the classPath).An example of the methods available on the object
path_2is theexists()method. The snippet of code below shows how it is used:from pathlib import Path if path_2.exists(): # the file exists do stuff
Link
See this article to learn about other differences between the two ways of managing paths with Python: Paths in Python: Comparing os.path and pathlib modules
Hello. I'm using windows and I want to make a new file in a directory if it doesn't exist yet.
I've read many people say that if you just use os.path.join() you don't have to worry about turning "\" into "/" manually. You don't have to worry about copying file names as paths. So i tried it because I want to do things not like an idiot, but the output of my os.path.join() still has "\". And it doesn't put a separator after "C:".
So what is the advantage of "~ just using os.path.join() like you're supposed to~"?
I understand that you can use .replace("\\","/") but what's the advantage of using os.path.join if I can just do that to a string? It seems like typing out the entire folder path in os.path.join is more work that copying and pasting it from your file window. Am i missing something?
I read the documentation here => os.path.join but I didn't find the explanation very clear. I am presuming it properly formats the path rather than just concatenating it , but that's just an assumption, I'd like to know exactly how it works.
The latter strings shouldn't start with a slash. If they start with a slash, then they're considered an "absolute path" and everything before them is discarded.
Quoting the Python docs for os.path.join:
If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.
Note on Windows, the behaviour in relation to drive letters, which seems to have changed compared to earlier Python versions:
On Windows, the drive letter is not reset when an absolute path component (e.g.,
r'\foo') is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive,os.path.join("c:", "foo")represents a path relative to the current directory on driveC:(c:foo), notc:\foo.
The idea of os.path.join() is to make your program cross-platform (linux/windows/etc).
Even one slash ruins it.
So it only makes sense when being used with some kind of a reference point like
os.environ['HOME'] or os.path.dirname(__file__).
Portable
Write filepath manipulations once and it works across many different platforms, for free. The delimiting character is abstracted away, making your job easier.
Smart
You no longer need to worry if that directory path had a trailing slash or not. os.path.join will add it if it needs to.
Clear
Using os.path.join makes it obvious to other people reading your code that you are working with filepaths. People can quickly scan through the code and discover it's a filepath intrinsically. If you decide to construct it yourself, you will likely detract the reader from finding actual problems with your code: "Hmm, some string concats, a substitution. Is this a filepath or what? Gah! Why didn't he use os.path.join?" :)
Will work on Windows with '\' and Unix (including Mac OS X) with '/'.
for posixpath here's the straightforward code
In [22]: os.path.join??
Type: function
String Form:<function join at 0x107c28ed8>
File: /usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py
Definition: os.path.join(a, *p)
Source:
def join(a, *p):
"""Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded."""
path = a
for b in p:
if b.startswith('/'):
path = b
elif path == '' or path.endswith('/'):
path += b
else:
path += '/' + b
return path
don't have windows but the same should be there with '\'