@@ -13,6 +13,7 @@ I'll create a Python script that uses argparse to parse a CSV file path, sorts a
13
13
# !/usr/bin/env python3
14
14
import argparse
15
15
import csv
16
+ import os
16
17
17
18
def main ():
18
19
# Set up argument parser
@@ -23,6 +24,14 @@ def main():
23
24
args = parser.parse_args()
24
25
25
26
try :
27
+ # Get the directory and filename
28
+ file_dir = os.path.dirname(args.file_path)
29
+ file_name = os.path.basename(args.file_path)
30
+
31
+ # Create output filename
32
+ base_name, ext = os.path.splitext(file_name)
33
+ output_file = os.path.join(file_dir, f " { base_name} _sorted { ext} " )
34
+
26
35
# Read the input CSV file
27
36
with open (args.file_path, ' r' ) as file :
28
37
reader = csv.reader(file )
@@ -35,11 +44,11 @@ def main():
35
44
sorted_values = sorted (values)
36
45
37
46
# Write to output file
38
- with open (' name_sorted.csv ' , ' w' , newline = ' ' ) as file :
47
+ with open (output_file , ' w' , newline = ' ' ) as file :
39
48
writer = csv.writer(file )
40
49
writer.writerow(sorted_values)
41
50
42
- print (f " Successfully sorted values and saved to name_sorted.csv " )
51
+ print (f " Successfully sorted values and saved to { output_file } " )
43
52
44
53
except FileNotFoundError :
45
54
print (f " Error: File ' { args.file_path} ' not found " )
@@ -48,7 +57,6 @@ def main():
48
57
49
58
if __name__ == " __main__" :
50
59
main()
51
-
52
60
```
53
61
54
62
This script:
0 commit comments