I recently wrote a python script to convert multiple files EOL’s from Unix
to DOS
and vice versa.
I am looking for tips to improve my code or if there is a better way of doing something that I have missed.
#!/usr/bin/env python3 import sys def main(): command, *filenames = sys.argv[1:] valid_commands = ['-d', '-u'] sys.tracebacklimit = None if not command in valid_commands: error = """'{command}' Provide the following arguments -u|d file [file2] [file3] ... flags: -u : converts DOS to UNIX -d : converts UNIX to DOS example command: ./eol -u foo.py bar.py""".format(command=command) raise ValueError(error) sys.exit(1) if filenames: convert(filenames, command) else: print("> no files to convert") def convert(files, command): for file in files: text = open(file, 'r').read() with open(file, 'w') as current: if command == '-u': format = 'UNIX' current.write(text.replace('\r\n', '\n')) elif command == '-d': format = 'DOS' current.write(text.replace('\n', '\r\n')) print("> converting file {filename} to {format} ...".format( filename=file, format=format)) if __name__ == "__main__": main()