|
1 | 1 | import sys
|
2 | 2 |
|
3 |
| -#print(sys.argv[0], sys.argv[1], sys.argv[2], sys.argv[3]) |
4 | 3 | if len(sys.argv) == 2: ## first item is the script name and second item is the file name sent as argument
|
5 |
| - ## take the file name from the command line and print the contents of it |
6 | 4 | file_name = sys.argv[1]
|
7 |
| - #print(f"file name is: {file_name}") |
8 | 5 |
|
9 | 6 | file_handle = open(file_name, 'r', encoding="utf-8")
|
10 | 7 | print(file_handle.read())
|
11 | 8 | file_handle.close()
|
12 |
| - ###################### |
13 | 9 | else:
|
14 | 10 | ## no file name. Take option from command line and print it. Shold exit ater 10 lines.
|
15 | 11 | if len(sys.argv) == 1 :
|
|
20 | 16 |
|
21 | 17 | elif sys.argv[1] == "-n":
|
22 | 18 | line_to_print = sys.argv[2]
|
23 |
| - file_name_to_work = sys.argv[3] |
24 |
| - #file_operation(file_name_to_work, sys.argv[1], line_to_print) |
25 |
| - #print(f"line to print {line_to_print}, file to work {file_name_to_work}") |
26 |
| - file_hdl = open(file_name_to_work, 'r', encoding="utf-8") |
27 |
| - for i in range(int(line_to_print)): |
28 |
| - print(file_hdl.readline()) |
29 |
| - file_hdl.close() |
| 19 | + files = sys.argv[3:] |
| 20 | + if len(files) > 1: |
| 21 | + for fileName in files: |
| 22 | + print(f"==> {fileName} <==") |
| 23 | + filehdl = open(fileName, 'r', encoding="utf-8") |
| 24 | + for i in range(int(line_to_print)): |
| 25 | + line = filehdl.readline() |
| 26 | + if line == "": ## end of file has been reached |
| 27 | + break |
| 28 | + print(line) |
| 29 | + filehdl.close() |
| 30 | + else: |
| 31 | + file_name_to_work = sys.argv[3] |
| 32 | + file_hdl = open(file_name_to_work, 'r', encoding="utf-8") |
| 33 | + for i in range(int(line_to_print)): |
| 34 | + line = file_hdl.readline() |
| 35 | + if line == "": ## end of file has been reached |
| 36 | + break |
| 37 | + print(line) |
| 38 | + |
| 39 | + file_hdl.close() |
30 | 40 |
|
31 | 41 | elif sys.argv[1] == "-c":
|
32 | 42 | chars_to_print = sys.argv[2]
|
|
0 commit comments