我想做的是从一个文件中取出 4 行,如下所示:
@blablabla
blablabla #this string needs to match the amount of characters in line 4
!blablabla
blablabla #there is a string here
这种情况持续了数百次。
我逐行阅读整个内容,对第四行进行更改,然后希望将第二行的字符数与第四行的字符数相匹配。
我不知道如何在更改第四行后“回溯”并更改第二行。
with fileC as inputA:
for line1 in inputA:
line2 = next(inputA)
line3 = next(inputA)
line4 = next(inputA)
是我目前正在使用的,因为它可以让我同时处理 4 行,但必须有更好的方法,因为在写掉文件时会导致各种问题。我可以使用什么作为替代方案?
最佳答案
你可以这样做:
with open(filec , 'r') as f:
lines = f.readlines() # readlines creates a list of the lines
要访问第 4 行并对其执行某些操作,您将访问:
lines[3] # as lines is a list
第 2 行
lines[1] # etc.
如果你愿意,你可以将你的行写回文件
编辑:
关于您的评论,可能是这样的:
def change_lines(fileC):
with open(fileC , 'r') as f:
while True:
lines = []
for i in range(4):
try:
lines.append(f.next()) # f.next() returns next line in file
except StopIteration: # this will happen if you reach end of file before finding 4 more lines.
#decide what you want to do here
return
# otherwise this will happen
lines[2] = lines[4] # or whatever you want to do here
# maybe write them to a new file
# remember you're still within the for loop here
编辑:
因为你的文件平均分成四份,所以这是有效的:
def change_lines(fileC):
with open(fileC , 'r') as f:
while True:
lines = []
for i in range(4):
try:
lines.append(f.next())
except StopIteration:
return
code code # do something with lines here
# and write to new file etc.
关于python - 在 python 中读取/编辑多行的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21518823/