Last active
December 8, 2015 03:25
-
-
Save fredcallaway/eb5d996749ed7e23978f to your computer and use it in GitHub Desktop.
Adds parentheses to print statements in a python file.
This file contains 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
import re | |
def add_print_parentheses(file_name): | |
match = None # a regex match when we are in a print statment | |
lines = [] | |
with open(file_name) as file: | |
for line in file: | |
line = line.rstrip() | |
if match: # we are in a print statement | |
indentation = re.match(r'[ ]*', line).span()[1] | |
if indentation > match_indentation: | |
match_lines.append(line) | |
else: | |
# the last line was the final line in the print statement | |
match_lines[-1] = match_lines[-1] + ')' | |
lines.extend(match_lines) | |
lines.append(line) | |
match = None | |
else: | |
match = re.match(r'([ ]*)print', line) | |
if match: | |
match_indentation = match.span(1)[1] | |
match_len = match.span()[1] | |
match_lines = [line[:match_len] + '(' + line[match_len+1:]] | |
else: | |
lines.append(line) | |
with open(file_name + '3', 'w+') as file: | |
file.write('\n'.join(lines)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment