
Python pathlib: How to get the files and directories in the current directory in Python
How to get all the items of the current directory in Python:
from pathlib import Path
# current file
file = Path(__file__)
print(file) # /Users/serif/python/test/main.py
print(type(file)) # <class 'pathlib.PosixPath'>
# current directory
parent = Path(__file__).parent
print(parent) # /Users/serif/python/test
# items in parent
items = parent.iterdir()
for item in items:
print(item)
# /Users/serif/python/test/util
# /Users/serif/python/test/game.py
# /Users/serif/python/test/__pycache__
# /Users/serif/python/test/main.py
# /Users/serif/python/test/.idea
First, import Path
from pathlib and get the PosixPath object of the current directory. __file__
is the current file path.
The iterdir()
returns the items in a directory. Each is actually a PosixPath object representing the path of a file or directory.
Get only directories in the current directory
from pathlib import Path
parent = Path(__file__).parent
items = parent.iterdir()
for item in items:
if item.is_dir():
print(item.as_posix())
# /Users/serif/python/test/util
# /Users/serif/python/test/__pycache__
# /Users/serif/python/test/.idea
The is_dir()
checks if the path is a directory.
Get only files in the current directory
from pathlib import Path
parent = Path(__file__).parent
items = parent.iterdir()
for item in items:
if item.is_file():
print(item.as_posix())
# /Users/serif/python/test/game.py
# /Users/serif/python/test/main.py
The is_file()
checks if the path is a file.
Absolute path
from pathlib import Path
p = Path(__file__)
p1 = p.as_posix()
p2 = p.absolute()
print(p1) # /Users/serif/python/test/main.py
print(p2) # /Users/serif/python/test/main.py
The as_posix()
and absolute()
returns the absolute path.
Comments
Powered by Markdown