Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion for using pathlib instead of os.path library #61

Open
mpvanderschelling opened this issue Dec 6, 2023 · 0 comments
Open

Comments

@mpvanderschelling
Copy link

This is merely a suggestion, but I think it would be beneficial to use the pathlib library instead of the os.path library. The pathlib library is more modern and has a more object-oriented approach to working with file paths. It also has better support for working with different operating systems.

I have created a code snippet of the same code but with pathlib instead of os.path:

def remove_files(
    directory: str,
    file_types: list = [".log", ".lck", ".SMABulk",
                        ".rec", ".SMAFocus",
                        ".exception", ".simlog", ".023", ".exception"],
) -> None:
    """Remove files of specified types in a directory.

    Parameters
    ----------
    directory : str
        Target folder.
    file_types : list
        List of file extensions to be removed.
    """
    # Create a Path object for the directory
    dir_path = Path(directory)

    for target_file in file_types:
        # Use glob to find files matching the target extension
        target_files = dir_path.glob(f"*{target_file}")

        # Remove the target files if they exist
        for file in target_files:
            if file.is_file():
                file.unlink()

Assignees:
Labels:

@staticmethod
def remove_files(
directory: str,
file_types: list = [
".log",
".lck",
".SMABulk",
".rec",
".SMAFocus",
".exception",
".simlog",
".023",
".exception",
],
) -> None:
"""remove file
Parameters
----------
directory : str
target folder
file_type : str
file name
"""
# get all files in this folder
all_files = os.listdir(directory)
for target_file in file_types:
# get the target file names
filtered_files = [
file for file in all_files if file.endswith(target_file)
]
# remove the target files is existed
for file in filtered_files:
path_to_file = os.path.join(directory, file)
if os.path.exists(path_to_file):
os.remove(path_to_file)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant