SHARE
TWEET

sort csv by fieldnames and write a new csv file

DeaD_EyE Dec 3rd, 2018 (edited) 90 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import csv
  2. from pathlib import Path
  3. import sys
  4.  
  5.  
  6. def sort_csv(file):
  7.     '''
  8.    This function sorts csv file alphabetical by header.
  9.    The output is written to the file new_ + filename
  10.    The dialect should be detected automatically.
  11.    '''
  12.     sniffer = csv.Sniffer()
  13.     source = Path(file)
  14.     destination = source.with_name('new_' + source.stem).with_suffix(source.suffix)
  15.     with source.open() as fd_in, destination.open('w') as fd_out:
  16.         dialect = sniffer.sniff(fd_in.read(2048))
  17.         fd_in.seek(0)
  18.         reader = csv.DictReader(fd_in, dialect=dialect)
  19.         fields = sorted(reader.fieldnames)
  20.         writer = csv.DictWriter(fd_out, fields, dialect=dialect)
  21.         writer.writeheader()
  22.         for row in reader:
  23.             writer.writerow(row)
  24.  
  25.  
  26. if __name__ == '__main__':
  27.     if len(sys.argv) == 2:
  28.         try:
  29.             sort_csv(sys.argv[1])
  30.         except Exception as e:
  31.             print('Got the exception:', e, file=sys.stderr)
  32.         sys.exit(0)
  33.     else:
  34.         print(f'{sys.argv[0]} source_file.csv', file=sys.stderr)
  35.         sys.exit(1)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top