Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import csv
- from pathlib import Path
- import sys
- def sort_csv(file):
- '''
- This function sorts csv file alphabetical by header.
- The output is written to the file new_ + filename
- The dialect should be detected automatically.
- '''
- sniffer = csv.Sniffer()
- source = Path(file)
- destination = source.with_name('new_' + source.stem).with_suffix(source.suffix)
- with source.open() as fd_in, destination.open('w') as fd_out:
- dialect = sniffer.sniff(fd_in.read(2048))
- fd_in.seek(0)
- reader = csv.DictReader(fd_in, dialect=dialect)
- fields = sorted(reader.fieldnames)
- writer = csv.DictWriter(fd_out, fields, dialect=dialect)
- writer.writeheader()
- for row in reader:
- writer.writerow(row)
- if __name__ == '__main__':
- if len(sys.argv) == 2:
- try:
- sort_csv(sys.argv[1])
- except Exception as e:
- print('Got the exception:', e, file=sys.stderr)
- sys.exit(0)
- else:
- print(f'{sys.argv[0]} source_file.csv', file=sys.stderr)
- sys.exit(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement