[英]Replace string in first 3 lines of a file
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: 使用python,我想用X替换前3行。例如:
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? 关于仅替换前三个的任何建议,或者关于line.replace为什么不尊重前三个的建议?
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()
. 请注意使用fileinput.input()
而不是fileinput.FileInput()
。 The .input()
call establishes global state, including the ability to call .filelineno()
. .input()
调用建立全局状态,包括调用.filelineno()
的能力。
Note the use of fileinput.filelineno()
to determine the line number. 请注意使用fileinput.filelineno()
来确定行号。 The program performes the replacement on the first three lines. 该程序在前三行执行替换。
Note the use of .rstrip('\\n')
to remove the original newline character. 请注意使用.rstrip('\\n')
删除原始换行符。 A newline will be implicitly added by the print
operation. 换行将通过print
操作隐式添加。
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. 在for循环中,这意味着您要在每行中最多替换3个B。 (Not 3 B's in the whole file.) (整个文件中没有3B。)
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.) 要执行您喜欢的操作(在Python中),您可以为每次读取的行增加一个计数器,并且仅在您的计数器小于3时才进行替换(如果从1开始对行进行编号,则为4)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.