Skip to content

Instantly share code, notes, and snippets.

@rhngla
Created July 3, 2020 19:49
Show Gist options
  • Save rhngla/cde1d9f25149810b3bb85f6c7d8b6559 to your computer and use it in GitHub Desktop.
Save rhngla/cde1d9f25149810b3bb85f6c7d8b6559 to your computer and use it in GitHub Desktop.
pathlib examples
#Some simple file IO related operations
from pathlib import Path
#Below takes care of os based differences
dir_name = '/Users/Fruity/Local/datasets'
file_name = 'CTX_Hip_10x_counts.h5'
dir_path = Path(dir_name)
#Use forward slashes to combine path
file_path = dir_path / file_name
#Paths can be converted to strings:
str(dir_path)
#Checking existence:
print(dir_path.exists())
#Check specifically if directory or file
print(dir_path.is_dir())
print(dir_path.is_file())
#Listing files that match a pattern in path
all_files = Path(dir_path).glob('*.h5')
all_files_list = list(all_files)
print(all_files_list)
#Pattern matching also like this:
list(dir_path.glob('*.h5'))
#Get current working directory
Path.cwd()
#Chop up the path
print(file_path.parts())
print(file_path.parent())
#Can check for duplicate files
dir_name = '/Users/Fruity/Local/datasets'
file_1 = 'CTX_Hip_10x_counts.h5'
file_2 = 'CTX_Hip_SS_counts.h5'
file_1_path = Path(dir_name / file_1)
file_2_path = Path(dir_name / file_2)
file_1_path.samefile(file_2_path) #True/False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment