-
Notifications
You must be signed in to change notification settings - Fork 4
/
remove_comments.py
35 lines (30 loc) · 1.15 KB
/
remove_comments.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def remove_comments(inputFile, outputFile):
'''
Args:
inputFile (str): path of the file to remove commments from.
outputFile (str): paths of the file to save after removing comments.
Returns:
bool: The return value. True for success, False otherwise.
'''
with open(inputFile, 'r') as f:
lines = f.readlines()
with open(outputFile, 'w') as f:
for line in lines:
# Keep the Shebang line
if line[0:2] == "#!":
f.writelines(line)
# Also keep existing empty lines
elif not line.strip():
f.writelines(line)
# But remove comments from other lines
else:
line = line.split('#')
stripped_string = line[0].rstrip()
# Write the line only if the comment was after the code.
# Discard lines that only contain comments.
if stripped_string:
f.writelines(stripped_string)
f.writelines('\n')
return True
if __name__ == '__main__':
remove_comments('detection.py', 'detection_no_comments.py')