1+ import argparse
2+ import os
3+ from pathlib import Path
4+
5+ # ===== Argument Handling =====
6+ parser = argparse .ArgumentParser (
7+ prog = "cat" ,
8+ description = "Prints file content" ,
9+ )
10+
11+ parser .add_argument ("-b" , action = "store_true" , help = "Numbers lines that aren't empty" )
12+ parser .add_argument ("-n" , action = "store_true" , help = "Numbers all lines" )
13+ parser .add_argument ("file_names" , nargs = "*" , help = "Files or folders to display" )
14+
15+ args = parser .parse_args ()
16+
17+ # ===== cat Procedure =====
18+ def cat (args ):
19+ cwd = os .getcwd ()
20+ all_files_contents = read_files (args .file_names , cwd )
21+ execute_flags (all_files_contents )
22+ print_lines (all_files_contents )
23+
24+ # ===== Extracting Data from Arguments =====
25+ def read_files (file_names , cwd ):
26+ all_files_contents = []
27+
28+ for file_name in file_names :
29+ file_content = read_file (file_name , cwd )
30+ all_files_contents .append (file_content .splitlines ())
31+ return all_files_contents
32+
33+ def read_file (file_name , cwd ):
34+ file_path = Path (cwd ) / file_name
35+ with open (file_path , "r" , encoding = "utf-8" ) as f :
36+ return f .read ().rstrip ()
37+
38+ # ===== Flag Handling =====
39+ def execute_flags (all_files_contents ):
40+ if args .b :
41+ line_number = 1
42+ for file_content in all_files_contents :
43+ for index , line in enumerate (file_content ):
44+ if line != "" :
45+ file_content [index ] = f"{ line_number :>6} \t { line } "
46+ line_number += 1
47+
48+ elif args .n :
49+ for file_idx , file_content in enumerate (all_files_contents ):
50+ all_files_contents [file_idx ] = [
51+ f"{ line_idx :>6} \t { line } "
52+ for line_idx , line in enumerate (file_content , start = 1 )
53+ ]
54+
55+ def make_list (output_string ):
56+ return output_string .replace ("\t " , "\n " ).replace ("\n \n " , "\n " )
57+
58+ # ===== Print Output =====
59+ def print_lines (all_files_contents ):
60+ for file_content in all_files_contents :
61+ for line in file_content :
62+ print (line )
63+
64+ # ===== Run cat =====
65+ cat (parser .parse_args ())
0 commit comments