|
| 1 | +--- |
| 2 | +title: CSV Sorter Script |
| 3 | +lang: en |
| 4 | +layout: post |
| 5 | +audio: false |
| 6 | +translated: false |
| 7 | +generated: true |
| 8 | +--- |
| 9 | + |
| 10 | +I'll create a Python script that uses argparse to parse a CSV file path, sorts a single line of comma-separated values alphabetically, and outputs the result to a file named "name_sorted.csv". |
| 11 | + |
| 12 | +```python |
| 13 | +#!/usr/bin/env python3 |
| 14 | +import argparse |
| 15 | +import csv |
| 16 | + |
| 17 | +def main(): |
| 18 | + # Set up argument parser |
| 19 | + parser = argparse.ArgumentParser(description='Sort a single-line CSV file alphabetically') |
| 20 | + parser.add_argument('file_path', help='Path to the input CSV file') |
| 21 | + |
| 22 | + # Parse arguments |
| 23 | + args = parser.parse_args() |
| 24 | + |
| 25 | + try: |
| 26 | + # Read the input CSV file |
| 27 | + with open(args.file_path, 'r') as file: |
| 28 | + reader = csv.reader(file) |
| 29 | + # Get the first line only |
| 30 | + for row in reader: |
| 31 | + values = row |
| 32 | + break |
| 33 | + |
| 34 | + # Sort the values alphabetically |
| 35 | + sorted_values = sorted(values) |
| 36 | + |
| 37 | + # Write to output file |
| 38 | + with open('name_sorted.csv', 'w', newline='') as file: |
| 39 | + writer = csv.writer(file) |
| 40 | + writer.writerow(sorted_values) |
| 41 | + |
| 42 | + print(f"Successfully sorted values and saved to name_sorted.csv") |
| 43 | + |
| 44 | + except FileNotFoundError: |
| 45 | + print(f"Error: File '{args.file_path}' not found") |
| 46 | + except Exception as e: |
| 47 | + print(f"Error: {e}") |
| 48 | + |
| 49 | +if __name__ == "__main__": |
| 50 | + main() |
| 51 | + |
| 52 | +``` |
| 53 | + |
| 54 | +This script: |
| 55 | +1. Uses argparse to get the input file path |
| 56 | +2. Opens the CSV file and reads only the first line |
| 57 | +3. Sorts the values alphabetically |
| 58 | +4. Writes the sorted values to "name_sorted.csv" |
| 59 | + |
| 60 | +To run the script, save it to a file (e.g., "sort_csv.py"), make it executable if needed, and run it with the path to your CSV file: |
| 61 | + |
| 62 | +``` |
| 63 | +python sort_csv.py path/to/your/file.csv |
| 64 | +``` |
| 65 | + |
| 66 | +Would you like me to explain any part of the code in more detail? |
0 commit comments