Created
May 23, 2020 13:05
-
-
Save nbroad1881/633f4c32c4a7dc796aecc5931ac4e9c3 to your computer and use it in GitHub Desktop.
Useful snippets for working with files and paths in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from pathlib import Path | |
# Absolute path of file | |
absolute_path = os.path.dirname(os.path.abspath(__file__)) | |
# OR | |
absolute_path = Path(__file__).resolve() | |
# List contents of directory | |
os.listdir('dirname-or-blank-for-current-dir') | |
Path("dir").ls() | |
# Iterate through directory | |
for f in Path("dir").iterdir(): | |
# Get current directory | |
os.getcwd() | |
Path.cwd() # static method | |
# check if file or directory exists | |
os.is_file("file") | |
os.is_dir("dir") | |
Path("file-or-dir").exists() | |
Path("file").is_file() | |
Path("dir").is_dir() | |
# Concatenate path | |
# to get /first/second/third | |
os.path.join("first","second","third") | |
Path('first') / "second" / "third" | |
# Make a directory | |
os.mkdir("dir_name") | |
Path("new_dir").mkdir() | |
Path("/parents/that/dont/exist/new_dir").mkdir(parents=True) # add parents if they don't exist | |
Path("alrady_existing_dir").mkdir(exist_ok=True) # won't raise errors if it already exists | |
# Environment variables | |
os.environ['specific_env_var'] | |
os.environ #all env vars | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment