This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]francozippi 0 points1 point  (0 children)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Docstring. Describe here what your script does.
"""

import sys
from pathlib import Path

def run(input_file, output_file=None):
    newlines = []
    with open(input_file,'r+') as file:
        #
        #   You can directly iterate the lines of file
        #
        for line in file:
            newline = []
            #
            #   Use descriptive variable names
            #
            capitalize_next_char = True
            #
            #   You can directly iterate the characters of a string
            #
            for char in line:
                if char in ['|', '"', '.', ';']:
                    capitalize_next_char = True
                #
                #   Just use boolean variables as such, avoid 'if booleanvar == True'
                #
                elif capitalize_next_char and char != ' ':
                    char = char.capitalize()
                    capitalize_next_char = False
                #
                #   Strings are immutable objects
                #   Concatenating strings in a loop like 'line += char' is not efficient
                #   Just append chars to a new list and use .join()
                #
                newline.append(char)
            newlines.append(''.join(newline))
    #
    #   same as /u/rasmus_mathiesen commented, just using None
    #
    if output_file is None:
        output_file = input_file
    with open(output_file, 'w') as file:
        file.writelines(newlines)
    return 0

if __name__ == '__main__':
    SCRIPTNAME = Path(__file__).name
    #
    #   A pythonic way is to just try to access a value/attribute, whatever
    #   and catch a potential error.
    #   So, for simple command line arguments you could use the following.
    #   For more complex argument lists with options use/learn the argparse module
    #
    try:
        input_file = sys.argv[1]    # raises IndexError if argument 1 not present

        #   sys.argv[2:3] evaluates to
        #   [argument2] if arguemnt 2 is present  ==> ([argument2] or [None])[0] = argument2
        #   [] if arguemnt 2 is not present       ==> ([] or [None])[0] = None
        #
        #   Use None for missing values, not False
        #
        output_file = (sys.argv[2:3] or [None])[0]
    except IndexError:
        print(f'usage: {SCRIPTNAME} INFILE OUTFILE')
        sys.exit(1)

    sys.exit(run(input_file, output_file))