fs¶
file-system related
- List directory
os.listdir(path) -> [a, b, ...]
# depth = 1
(dirpath, dirnames, filenames) = next(os.walk(path))
- Walk directory and files recursively
for (dirpath, dirnames, filenames) in os.walk(path):
# ...
- Current directory (
pathlib
)
from pathlib import Path
Path.cwd() # Get current dir
full_path = Path(__file__).resolve()
dir_name = full_path.parent
- Current directory (
os
)
os.getcwd() # Get current dir
os.chdir('/usr') # Change current dir
__file__ # Current filename
dir_name = os.path.dirname(full_path)
full_path = os.path.realpath(__file__)
# Spilt
path, filename = os.path.split(full_path)
- Delete a file
Path(file_path).unlink() == os.remove(file_path)
rm -r
shutil.rmtree(path)
- Delete a dir
Path(dir_path).rmdir() == os.rmdir(dir_path)
- touch a file
Path(path).touch()
os
and pathlib
¶
See Also¶
References¶
pathlib — Object-oriented filesystem paths
https://docs.python.org/3/library/pathlib.html
os — Miscellaneous operating system interfaces
https://docs.python.org/3/library/os.html