Created
May 4, 2023 06:02
-
-
Save shimo164/00f39429bfc11989f0b359b784977d80 to your computer and use it in GitHub Desktop.
This script searches for Python files in a given directory and its subdirectories, then finds and prints the longest line of each file if the line length is greater than a specified threshold.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This script searches for Python files in a given directory and its | |
subdirectories, then finds and prints the longest line of each file if the | |
line length is greater than a specified threshold. | |
Output: | |
- The file path. | |
- The line number of the longest line. | |
- The first 100 characters of the longest line. | |
- The length of the longest line. | |
Args in main(): | |
dir_root (str): The root directory to search for Python files. | |
length_threshold (int, optional): The minimum length required to print | |
the line. Defaults to 80. | |
""" | |
import pathlib | |
def get_python_files(dir_root: str) -> list[str]: | |
file_list = [str(p) for p in pathlib.Path(dir_root).glob('**/*.py')] | |
return file_list | |
def find_longest_line(file_path: str) -> tuple[str, int, int]: | |
with open(file_path) as f: | |
max_length_line = '' | |
max_length = 0 | |
line_number = 0 | |
for i, line in enumerate(f, start=1): | |
if len(line) > max_length: | |
max_length_line = line | |
max_length = len(line) | |
line_number = i | |
return max_length_line, max_length, line_number | |
def print_longest_line_info( | |
file_path: str, | |
max_length_line: str, | |
max_length: int, | |
line_number: int, | |
length_threshold: int = 80, | |
print_length: int = 100, | |
): | |
if max_length > length_threshold: | |
print(file_path) | |
print(f"Line {line_number}: {max_length_line[:print_length]}") | |
print(f"Length: {max_length}") | |
print("---") | |
def main(): | |
dir_to_check = '/path/to/your/dir/' | |
python_files = get_python_files(dir_to_check) | |
length_threshold = 80 | |
for file_path in python_files: | |
max_length_line, max_length, line_number = find_longest_line(file_path) | |
print_longest_line_info( | |
file_path, max_length_line, max_length, line_number, length_threshold | |
) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment