Skip to content

Instantly share code, notes, and snippets.

@chapmanjacobd
Created December 22, 2023 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chapmanjacobd/c9e4a17412c7aa21a53fb9f6ae7db630 to your computer and use it in GitHub Desktop.
Save chapmanjacobd/c9e4a17412c7aa21a53fb9f6ae7db630 to your computer and use it in GitHub Desktop.
def get_file_part(file_path, specifier):
size = file_path.stat().st_size
if specifier.isdigit():
specifier = int(specifier)
if specifier > 0:
with file_path.open('rb') as file:
return file.read(specifier)
else:
with file_path.open('rb') as file:
file.seek(max(size + specifier, 0))
return file.read(-specifier)
elif specifier.endswith('%'):
percent = float(specifier[:-1])
bytes_to_read = int(size * (percent / 100))
if specifier.startswith('-'):
with file_path.open('rb') as file:
file.seek(max(size - bytes_to_read, 0))
return file.read(bytes_to_read)
else:
with file_path.open('rb') as file:
return file.read(bytes_to_read)
elif '-' in specifier:
start, end = map(int, specifier.split('-'))
if end == 0:
end = size
with file_path.open('rb') as file:
file.seek(start)
return file.read(end - start)
else:
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment