To be even more pedantic, the most python doc consistent answer would be:
mypath = os.path.join('c:', os.sep, 'sourcedir')
Since you also need os.sep for the posix root path:
mypath = os.path.join(os.sep, 'usr', 'lib')
Answer from AndreasT on Stack OverflowPython os.path.join on Windows - Stack Overflow
pathlib.Path vs. os.path.join in Python - Stack Overflow
correct way of using os.path.join() in python - Stack Overflow
python - How to join paths nice way? - Stack Overflow
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?
To be even more pedantic, the most python doc consistent answer would be:
mypath = os.path.join('c:', os.sep, 'sourcedir')
Since you also need os.sep for the posix root path:
mypath = os.path.join(os.sep, 'usr', 'lib')
Windows has a concept of current directory for each drive. Because of that, "c:sourcedir" means "sourcedir" inside the current C: directory, and you'll need to specify an absolute directory.
Any of these should work and give the same result, but I don't have a Windows VM fired up at the moment to double check:
"c:/sourcedir"
os.path.join("/", "c:", "sourcedir")
os.path.join("c:/", "sourcedir")
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
On python 3.8.0 it seem to work as expected.
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
filepath = 'files/one.txt'
request_path = os.path.join(BASE_DIR, filepath)
print(request_path, filepath, BASE_DIR)
$ python -V
Python 3.8.0
$ python /tmp/a.py
/tmp/files/one.txt files/one.txt /tmp
You could use the f-string in python (see documentation).
In your case:
request_path = f"{BASE_DIR}/{filepath}"
Be aware that you need an extra slash "/" between your file location variables (BASE_DIR and filepath) to complete the full file location properly.
Hope this helps!
You can use normpath, realpath or abspath:
import os
goal_dir = os.path.join(os.getcwd(), "../../my_dir")
print goal_dir # prints C:/here/I/am/../../my_dir
print os.path.normpath(goal_dir) # prints C:/here/my_dir
print os.path.realpath(goal_dir) # prints C:/here/my_dir
print os.path.abspath(goal_dir) # prints C:/here/my_dir
consider to use os.path.abspath this will evaluate the absolute path
or One can use os.path.normpath this will return the normalized path (Normalize path, eliminating double slashes, etc.)
One should pick one of these functions depending on requirements
In the case of abspath In Your example, You don't need to use os.path.join
os.path.abspath("../../my_dir")
os.path.normpath should be used if you are interested in the relative path.
>>> os.path.normpath("../my_dir/../my_dir")
'../my_dir'
Other references for handling with file paths:
- pathlib - Object-oriented filesystem paths
- os.pathโ Common pathname manipulations