- abspath
- It returns the absolute path of current working directory with file name.
file_name = 'GFG.txt'
print(os.path.abspath(file_name))
>>>
/home/geeks/Desktop/gfg/GFG.txt
- chdir
Change directory.
file_name = 'GFG.txt'
os.chdir("/home/geeks/")
print(os.path.abspath(file_name))
>>>
/home/geeks/GFG.txt #refer previous code
- basename
- It returns only the file name except for the parent path.
- Split by '/', return the last one.
- If it ends with '/', it returns an empty.
path = "/d/workspace/dir1/dir2/dir3"
print(f"[1] '{os.path.basename(path)}'")
>>>
[1] 'dir3'
path = "/d/workspace/dir1/dir2"
print(f"[2] '{os.path.basename(path)}'")
>>>
[2] 'dir2'
path = "/d/workspace/dir1/dir2/"
print(f"[3] '{os.path.basename(path)}'")
>>>
[3] ''
path = "/d/workspace/dir1/dir2/test.py"
print(f"[4] '{os.path.basename(path)}'")
>>>
[4] 'test.py'
- os.path.join
os.path.join(path, *paths)
- path: A path-like object representing a file system path.
- *path: A path-like object representing a file system path. It represents the path components to be joined. A path-like object is either a string or bytes object representing a path.
The Method that joins one or more path components intelligently. This method concatenates various path components with exactly one directory separator (‘/’) following each non-empty part except the last path component. If the last path component to be joined is empty then a directory separator (‘/’) is put at the end.
print("join(): " + os.path.join(os.path.abspath(os.path.dirname(__file__)), "file.py"))
>>>
join(): /Users/XXX/Desktop/os-path-join/file.py
- __file__ : Display the current file.
- os.path.dirname : Show the relative path
- os.path.abspath : Conver the path to an absolute path
join() considers it as a root if it contains a separate character ('/') in the directory.
print(os.path.join("dirA", "dirB", "/dirC"))
print(os.path.join("/dirA", "/dirB", "dirC"))
print(os.path.join("/dirA", "dirB", "dirC"))
>>>
/dirC
/dirB/dirC
/dirA/dirB/dirC
'Basic Python' 카테고리의 다른 글
getattr (0) | 2023.11.15 |
---|---|
sort VS sorted (0) | 2023.11.10 |
glob (0) | 2023.11.04 |
bytes VS bytearray (0) | 2023.10.30 |
pickle, dump, load (0) | 2023.10.24 |