在python中读取/编辑多行的方法 [英] Ways to read/edit multiple lines in python
问题描述
我想做的是从看起来像这样的文件中提取4行:
What i'm trying to do is to take 4 lines from a file that look like this:
@blablabla
blablabla #this string needs to match the amount of characters in line 4
!blablabla
blablabla #there is a string here
这种情况持续了数百次.
This goes on for a few hundred times.
我逐行阅读整个内容,更改为第四行,然后将第二行的字符数与第四行中的数量匹配.
I read the entire thing line by line, make a change to the fourth line, then want to match the second line's character count to the amount in the fourth line.
更改第四行后,我不知道如何回溯"并更改第二行.
I can't figure out how to "backtrack" and change the second line after making changes to the fourth.
with fileC as inputA:
for line1 in inputA:
line2 = next(inputA)
line3 = next(inputA)
line4 = next(inputA)
是我当前正在使用的,因为它可以让我同时处理4行,但是必须有一种更好的方法,因为在写出文件时会引起各种各样的问题.我可以用什么替代呢?
is what i'm currently using, because it lets me handle 4 lines at the same time, but there has to be a better way as causes all sorts of problems when writing away the file. What could I use as an alternative?
推荐答案
您可以这样做:
with open(filec , 'r') as f:
lines = f.readlines() # readlines creates a list of the lines
访问第4行并对其进行操作,您将访问:
to access line 4 and do something with it you would access:
lines[3] # as lines is a list
第2行
lines[1] # etc.
然后,您可以根据需要将行写回到文件中
You could then write your lines back into a file if you wish
关于您的评论,也许是这样的:
Regarding your comment, perhaps something like this:
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
由于您的文件平均分为四个部分,因此可以:
Since your file divides into fours evenly, this works:
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中读取/编辑多行的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!