Skip to content

Instantly share code, notes, and snippets.

@coxley
Created April 14, 2016 15:55
Show Gist options
  • Save coxley/45ada9770423c13a8a3ff8f68c54f02d to your computer and use it in GitHub Desktop.
Save coxley/45ada9770423c13a8a3ff8f68c54f02d to your computer and use it in GitHub Desktop.
#!/bin/env python
def toggle_comment(lines, filename, startswith=False):
'''Toggle comment on lines in filename
Options:
lines (list): lines to comment.
filename (str): filname
startswith (bool): allows providing start of a line vs exact matching
'''
uncommented_lines = ['%s\n' % line for line in lines]
commented_lines = ['# %s' % line for line in uncommented_lines]
new_lines = []
with open(filename) as f:
file_lines = f.readlines()
for file_line in file_lines:
if file_line in uncommented_lines:
file_line = '# %s' % file_line
elif file_line in commented_lines:
file_line = file_line[2:]
new_lines.append(file_line)
with open(filename, 'w') as f:
f.writelines(new_lines)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment