Skip to content

Commit

Permalink
return path to decompressed file from decompress_file()
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh committed Aug 7, 2023
1 parent 2b91561 commit 9fea74d
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions monty/shutil.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""
Copying and zipping utilities. Works on directories mostly.
"""
"""Copying and zipping utilities. Works on directories mostly."""
from __future__ import annotations

import os
import shutil
Expand All @@ -20,7 +19,6 @@ def copy_r(src, dst):
src (str): Source folder to copy.
dst (str): Destination folder.
"""

abssrc = os.path.abspath(src)
absdst = os.path.abspath(dst)
try:
Expand Down Expand Up @@ -90,12 +88,12 @@ def compress_dir(path, compression="gz"):
compression (str): A compression mode. Valid options are "gz" or
"bz2". Defaults to gz.
"""
for parent, subdirs, files in os.walk(path):
for parent, _subdirs, files in os.walk(path):
for f in files:
compress_file(os.path.join(parent, f), compression=compression)


def decompress_file(filepath):
def decompress_file(filepath) -> str:
"""
Decompresses a file with the correct extension. Automatically detects
gz, bz2 or z extension.
Expand All @@ -104,14 +102,20 @@ def decompress_file(filepath):
filepath (str): Path to file.
compression (str): A compression mode. Valid options are "gz" or
"bz2". Defaults to "gz".
Returns:
str: The decompressed file path.
"""
toks = filepath.split(".")
file_ext = toks[-1].upper()
if file_ext in ["BZ2", "GZ", "Z"]:
with open(".".join(toks[0:-1]), "wb") as f_out, zopen(filepath, "rb") as f_in:
out_file = ".".join(toks[0:-1])
with zopen(filepath, "rb") as f_in, open(out_file, "wb") as f_out:
f_out.writelines(f_in)
os.remove(filepath)

return out_file


def decompress_dir(path):
"""
Expand All @@ -120,15 +124,15 @@ def decompress_dir(path):
Args:
path (str): Path to parent directory.
"""
for parent, subdirs, files in os.walk(path):
for parent, _subdirs, files in os.walk(path):
for f in files:
decompress_file(os.path.join(parent, f))


def remove(path, follow_symlink=False):
"""
Implements a remove function that will delete files, folder trees and
symlink trees
symlink trees.
1.) Remove a file
2.) Remove a symlink and follow into with a recursive rm if follow_symlink
Expand Down

0 comments on commit 9fea74d

Please sign in to comment.