在python中读取/编辑多行的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21518823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ways to read/edit multiple lines in python
提问by Roeben
What i'm trying to do is to take 4 lines from a file that look like this:
我想要做的是从一个看起来像这样的文件中取出 4 行:
@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)
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?
是我目前正在使用的,因为它可以让我同时处理 4 行,但是必须有更好的方法,因为在写掉文件时会导致各种问题。我可以用什么作为替代?
采纳答案by Totem
you could do:
你可以这样做:
with open(filec , 'r') as f:
lines = f.readlines() # readlines creates a list of the lines
to access line 4 and do something with it you would access:
要访问第 4 行并对其进行处理,您将访问:
lines[3] # as lines is a list
and for line 2
和第 2 行
lines[1] # etc.
You could then write your lines back into a file if you wish
如果你愿意,你可以将你的行写回一个文件
EDIT:
编辑:
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
EDIT:
编辑:
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.
回答by tijko
You could read the file with .readlinesand then index which ever line you want to change and write that back to the file:
您可以读取文件,.readlines然后索引要更改的行并将其写回文件:
rf = open('/path/to/file')
file_lines = rf.readlines()
rf.close()
line[1] = line[3] # trim/edit however you'd like
wf = open('/path/to/write', 'w')
wf.writelines(file_lines)
wf.close()
回答by FMc
Another way to do it:
另一种方法:
import sys
from itertools import islice
def read_in_chunks(file_path, n):
with open(file_path) as fh:
while True:
lines = list(islice(fh, n))
if lines: yield lines
else: break
for lines in read_in_chunks(sys.argv[1], 4):
print lines
Also relevant is the grouper()recipein the itertoolsmodule. In that case, you would need to filter out the Nonevalues before yielding them to the caller.
另外相关的是grouper()配方中的itertools模块。在这种情况下,您需要先过滤掉这些None值,然后再将它们交给调用者。

