Skip to content

Commit b9ef734

Browse files
committedApr 14, 2025·
docs(notes): update 2025-04-14-csv-sort-en.md
1 parent 539b898 commit b9ef734

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed
 

Diff for: ‎notes/2025-04-14-csv-sort-en.md

+11-3
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ I'll create a Python script that uses argparse to parse a CSV file path, sorts a
1313
#!/usr/bin/env python3
1414
import argparse
1515
import csv
16+
import os
1617

1718
def main():
1819
# Set up argument parser
@@ -23,6 +24,14 @@ def main():
2324
args = parser.parse_args()
2425

2526
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+
2635
# Read the input CSV file
2736
with open(args.file_path, 'r') as file:
2837
reader = csv.reader(file)
@@ -35,11 +44,11 @@ def main():
3544
sorted_values = sorted(values)
3645

3746
# Write to output file
38-
with open('name_sorted.csv', 'w', newline='') as file:
47+
with open(output_file, 'w', newline='') as file:
3948
writer = csv.writer(file)
4049
writer.writerow(sorted_values)
4150

42-
print(f"Successfully sorted values and saved to name_sorted.csv")
51+
print(f"Successfully sorted values and saved to {output_file}")
4352

4453
except FileNotFoundError:
4554
print(f"Error: File '{args.file_path}' not found")
@@ -48,7 +57,6 @@ def main():
4857

4958
if __name__ == "__main__":
5059
main()
51-
5260
```
5361

5462
This script:

0 commit comments

Comments
 (0)
Please sign in to comment.