Skip to main content
added 52 characters in body
Source Link
  1. The encoding line is unnecessary as default is utf8

    The encoding line is unnecessary as default is utf8
  2. Similarly when opening a file, utf8 is assumed by default.

    Similarly when opening a file, utf8 is assumed by default.
  3. Instead of printing error messages, raise exceptions. Leave it to the code calling the function to decide what it does when an exception occurs.

    Instead of printing error messages, raise exceptions. Leave it to the code calling the function to decide what it does when an exception occurs.
  4. Instead of code that writes lines to a file, write code generating line. This separates the concerns. This code does not need to handle the IO, and the output to the file can easily be done with a single call to writelines()

    Instead of code that writes lines to a file, write code generating lines. This separates the concerns. This code does not need to handle the IO, and the output to the file can easily be done with a single call to writelines()
  5. As this is a script, add a section using the argparse module to handle command line arguments such as the target directory, and also to provide a help string for the user

    As this is a script, add a section using the argparse module to handle command line arguments such as the target directory, and also to provide a help string for the user
  6. Use Black to reformat your code!

    from pathlib import Path

    def write_into_file( folder, file_name: str = "stats_dossiers.txt", exist_ok: bool = False ) -> None: """ Summary : this function write into file_name the name of each file in directory targeted and weight associated in bytes. folder : directory targeted for analysis. file_name : name of file in .txt format, which will contain informations. """

    if not file_name.endswith(".txt"):
        raise ValueError(f"Expected file name with '.txt' extension, got: {file_name}")
    
    new_file = Path(folder, file_name)
    # Check if file already exists.
    if (not exist_ok) and new_file.exists():
        raise FileExistsError(new_File)
    
    def generate_stats(files, header="Name of file ; Size (Byte)\n"):
        "generates a sequence of lines each containing information about a file"
        if header:
            yield header
        for f in files:
            yield f"{str(f)} ; {f.stat().st_size}\n"
    
    with new_file.open("w") as stats_file:
        stats_file.writelines(generate_stats(Path(folder).iterdir()))
    

    if name == "main": write_into_file(folder=Path.cwd())

    Use Black to reformat your code!

from pathlib import Path


def write_into_file(
    folder, file_name: str = "stats_dossiers.txt", exist_ok: bool = False
) -> None:
    """
    __Summary__ : this function write into file_name the name of each file in directory targeted and weight associated in bytes.
    folder      : directory targeted for analysis.
    file_name   : name of file in .txt format, which will contain informations.
    """

    if not file_name.endswith(".txt"):
        raise ValueError(f"Expected file name with '.txt' extension, got: {file_name}")

    new_file = Path(folder, file_name)
    # Check if file already exists.
    if (not exist_ok) and new_file.exists():
        raise FileExistsError(new_File)

    def generate_stats(files, header="Name of file ; Size (Byte)\n"):
        "generates a sequence of lines each containing information about a file"
        if header:
            yield header
        for f in files:
            yield f"{str(f)} ; {f.stat().st_size}\n"

    with new_file.open("w") as stats_file:
        stats_file.writelines(generate_stats(Path(folder).iterdir()))


# # # # # GLOBAL VARIABLES # # # # #
# Define directory to analyze.
FOLDER = Path.cwd()

# Listing all folders in current directory.


if __name__ == "__main__":
    write_into_file(folder=FOLDER)
  1. The encoding line is unnecessary as default is utf8

  2. Similarly when opening a file, utf8 is assumed by default.

  3. Instead of printing error messages, raise exceptions. Leave it to the code calling the function to decide what it does when an exception occurs.

  4. Instead of code that writes lines to a file, write code generating line. This separates the concerns. This code does not need to handle the IO, and the output to the file can easily be done with a single call to writelines()

  5. As this is a script, add a section using the argparse module to handle command line arguments such as the target directory, and also to provide a help string for the user

  6. Use Black to reformat your code!

    from pathlib import Path

    def write_into_file( folder, file_name: str = "stats_dossiers.txt", exist_ok: bool = False ) -> None: """ Summary : this function write into file_name the name of each file in directory targeted and weight associated in bytes. folder : directory targeted for analysis. file_name : name of file in .txt format, which will contain informations. """

    if not file_name.endswith(".txt"):
        raise ValueError(f"Expected file name with '.txt' extension, got: {file_name}")
    
    new_file = Path(folder, file_name)
    # Check if file already exists.
    if (not exist_ok) and new_file.exists():
        raise FileExistsError(new_File)
    
    def generate_stats(files, header="Name of file ; Size (Byte)\n"):
        "generates a sequence of lines each containing information about a file"
        if header:
            yield header
        for f in files:
            yield f"{str(f)} ; {f.stat().st_size}\n"
    
    with new_file.open("w") as stats_file:
        stats_file.writelines(generate_stats(Path(folder).iterdir()))
    

    if name == "main": write_into_file(folder=Path.cwd())

  1. The encoding line is unnecessary as default is utf8
  2. Similarly when opening a file, utf8 is assumed by default.
  3. Instead of printing error messages, raise exceptions. Leave it to the code calling the function to decide what it does when an exception occurs.
  4. Instead of code that writes lines to a file, write code generating lines. This separates the concerns. This code does not need to handle the IO, and the output to the file can easily be done with a single call to writelines()
  5. As this is a script, add a section using the argparse module to handle command line arguments such as the target directory, and also to provide a help string for the user
  6. Use Black to reformat your code!

from pathlib import Path


def write_into_file(
    folder, file_name: str = "stats_dossiers.txt", exist_ok: bool = False
) -> None:
    """
    __Summary__ : this function write into file_name the name of each file in directory targeted and weight associated in bytes.
    folder      : directory targeted for analysis.
    file_name   : name of file in .txt format, which will contain informations.
    """

    if not file_name.endswith(".txt"):
        raise ValueError(f"Expected file name with '.txt' extension, got: {file_name}")

    new_file = Path(folder, file_name)
    # Check if file already exists.
    if (not exist_ok) and new_file.exists():
        raise FileExistsError(new_File)

    def generate_stats(files, header="Name of file ; Size (Byte)\n"):
        "generates a sequence of lines each containing information about a file"
        if header:
            yield header
        for f in files:
            yield f"{str(f)} ; {f.stat().st_size}\n"

    with new_file.open("w") as stats_file:
        stats_file.writelines(generate_stats(Path(folder).iterdir()))


# # # # # GLOBAL VARIABLES # # # # #
# Define directory to analyze.
FOLDER = Path.cwd()

# Listing all folders in current directory.


if __name__ == "__main__":
    write_into_file(folder=FOLDER)
Source Link

Here are my tips

  1. The encoding line is unnecessary as default is utf8

  2. Similarly when opening a file, utf8 is assumed by default.

  3. Instead of printing error messages, raise exceptions. Leave it to the code calling the function to decide what it does when an exception occurs.

  4. Instead of code that writes lines to a file, write code generating line. This separates the concerns. This code does not need to handle the IO, and the output to the file can easily be done with a single call to writelines()

  5. As this is a script, add a section using the argparse module to handle command line arguments such as the target directory, and also to provide a help string for the user

  6. Use Black to reformat your code!

    from pathlib import Path

    def write_into_file( folder, file_name: str = "stats_dossiers.txt", exist_ok: bool = False ) -> None: """ Summary : this function write into file_name the name of each file in directory targeted and weight associated in bytes. folder : directory targeted for analysis. file_name : name of file in .txt format, which will contain informations. """

    if not file_name.endswith(".txt"):
        raise ValueError(f"Expected file name with '.txt' extension, got: {file_name}")
    
    new_file = Path(folder, file_name)
    # Check if file already exists.
    if (not exist_ok) and new_file.exists():
        raise FileExistsError(new_File)
    
    def generate_stats(files, header="Name of file ; Size (Byte)\n"):
        "generates a sequence of lines each containing information about a file"
        if header:
            yield header
        for f in files:
            yield f"{str(f)} ; {f.stat().st_size}\n"
    
    with new_file.open("w") as stats_file:
        stats_file.writelines(generate_stats(Path(folder).iterdir()))
    

    if name == "main": write_into_file(folder=Path.cwd())