Reputation: 111
Is there a way to open a file (let's say a .py file) and comment a particular line already existent in the file? Or is there a way to create a piece of code that replaces that line with another one?
Upvotes: 0
Views: 1101
Reputation: 5535
Yes. You can open a file and read it line by line as,
with open('file.py') as f:
lines = f.readlines()
Search for the particular line as raw string or regular expression with an if condition and replace it like,
for n, line in enumerate(lines):
if(line == search_line):
lines[n] = new_line
Write to the same file like:
with open('file.py', 'w') as f:
f.write(''.join(lines))
Upvotes: 1
Reputation: 97
Here is a python solution that takes a file called commentFile.py
and comments out any line containing the string comment
.
wfile = open("commentFile.py","r+")
d = wfile.readlines()
wfile.seek(0)
allLines = []
for line in d:
if("comment" in line and "#" not in line):
allLines.append("#"+line)
else:
allLines.append(line)
wfile.writelines(allLines)
wfile.close()
Upvotes: 0
Reputation: 5108
How about just read in the file line by line and then append to an output file the lines either with or without a comment, depending on your needs.
For example to add the comment on each line starting with the string abc
you could do:
with open('in.txt', 'a') as outfile:
with open('test.txt', 'r') as infile:
for line in infile.readlines():
if line.startswith('abc'):
outfile.write(line.strip() + " # Here's abc\n")
else:
outfile.write(line)
This would make:
abc 1 # Here's abc
blabla 2
def 3
abc 4 # Here's abc
from the input file:
abc 1
blabla 2
def 3
abc 4
The check wether a line needs commented can also be searching by regex or by modifying my example a bit you could comment also certain line numbers. But that's up to you now to figure out.
Upvotes: 1