Last active
June 11, 2019 13:32
-
-
Save matschundbrei/77dfe6ca3fada4d76f2a3c77253035d5 to your computer and use it in GitHub Desktop.
Switch out the field separator in a csv (for easy import in Excel)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
small script to exchange the field separator in a CSV | |
""" | |
import csv | |
import argparse | |
import sys | |
def main(): | |
""" | |
main function | |
""" | |
errstate = False | |
parser = argparse.ArgumentParser(description='Switches the field separator in a csv.') | |
parser.add_argument('--source', '-s', dest='source', help='source file to read') | |
parser.add_argument('--dest', '-d', dest='dest', help='destination file to write') | |
parser.add_argument('--fssrc', dest='fss', help='field separator to use in source file', | |
default=',') | |
parser.add_argument('--fstgt', dest='fst', help='field separator to use in target file', | |
default=';') | |
parser.add_argument('--dialect', dest='dialect', help='csv dialect to use', default='excel') | |
args = parser.parse_args() | |
if args.source is None: | |
print('no sourcefile given') | |
errstate = True | |
elif args.dest is None: | |
print('no destfile given') | |
errstate = True | |
if errstate: | |
parser.print_help() | |
sys.exit() | |
else: | |
with open(args.source, newline='') as read: | |
reader = csv.reader(read, delimiter=args.fss) | |
with open(args.dest, 'w', newline='') as write: | |
writer = csv.writer(write, delimiter=args.fst, dialect=args.dialect) | |
writer.writerows(reader) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment