I have a file similar to this:
This is a letter B
This is a letter B
This is a letter B
This is a letter B
This is a letter B
This is a letter B
Using python, I'd like to replace the first 3 lines with an X. For example:
This is a letter X
This is a letter X
This is a letter X
This is a letter B
This is a letter B
This is a letter B
The code I'm using changes every line:
for line in fileinput.FileInput(File,inplace=1):
line = line.replace('B','x',3)
print line
Any suggestions on replacing the first 3 only or as to why the line.replace is not honoring the 3?
Thank you.
This program might do what you want:
import fileinput
File = 'bbb.txt'
for line in fileinput.input([File], inplace=1):
if fileinput.filelineno() <= 3:
line = line.replace('B', 'x')
print line.rstrip('\n')
Note the use of fileinput.input()
instead of fileinput.FileInput()
. The .input()
call establishes global state, including the ability to call .filelineno()
.
Note the use of fileinput.filelineno()
to determine the line number. The program performes the replacement on the first three lines.
Note the use of .rstrip('\\n')
to remove the original newline character. A newline will be implicitly added by the print
operation.
You are calling
line.replace('B','x',3)
inside the for-loop, which means you are replacing up to 3 B's in each line. (Not 3 B's in the whole file.)
To do what you like (in Python) you could increment a counter for each line read and only do the replacement if your counter is less than 3 (or 4, if you number lines starting at 1.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.