Skip to content

Instantly share code, notes, and snippets.

@khalido
Last active June 3, 2020 10:14
Show Gist options
  • Save khalido/0ec6a638870159143d904a0b695c01ee to your computer and use it in GitHub Desktop.
Save khalido/0ec6a638870159143d904a0b695c01ee to your computer and use it in GitHub Desktop.
[Dealing with files] #python
"""
For most purposes, the pathlib lib replaces all the with open() file stuff.
"""
from pathlib import Path
# to get the contents of a file
txt = Path(txt_file).read_text() # txt_file can be str or Path obj
bin_data = Path(binary_file).read_bytes() # binary_file can be str or Path obj
# write to a file
Path("a txt file.txt").write_text(txt)
Path("a binary file.bin").write_bytes(bin_data)
# to get a list of all files in the current dir with *.txt in the name
Path.cwd().glob('*.txt')
# or search recursively in current and all child subdirs
Path.cwd().rglob('*.txt')
# other useful stuff
p = Path("somefile.zip")
p.stat().st_size # size in bytes - /1024**2 for MB or **3 for GB
p.stat().st_ctime # creation time
p.stat().st_mtime # last modified time
# delete a file
p.unlink(missing_ok=True) # true means it doesn't raise error for missing files.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment