在Python中读取/编辑多行的方法

Roe*_*ben 4 python edit lines

我想做的是从文件中取出 4 行,如下所示:

@blablabla
blablabla #this string needs to match the amount of characters in line 4
!blablabla
blablabla #there is a string here
Run Code Online (Sandbox Code Playgroud)

这样持续了几百次。

我逐行阅读整个内容,对第四行进行更改,然后想要将第二行的字符数与第四行中的数量相匹配。

我不知道如何在更改第四行后“回溯”并更改第二行。

with fileC as inputA:
    for line1 in inputA:
        line2 = next(inputA)
        line3 = next(inputA)
        line4 = next(inputA)
Run Code Online (Sandbox Code Playgroud)

是我目前正在使用的,因为它可以让我同时处理 4 行,但是必须有更好的方法,因为在写掉文件时会导致各种问题。我可以用什么作为替代方案?

Tot*_*tem 6

你可以这样做:

with open(filec , 'r') as f:
    lines = f.readlines() # readlines creates a list of the lines
Run Code Online (Sandbox Code Playgroud)

要访问第 4 行并对其执行某些操作,您可以访问:

lines[3] # as lines is a list
Run Code Online (Sandbox Code Playgroud)

对于第 2 行

lines[1] # etc.
Run Code Online (Sandbox Code Playgroud)

如果您愿意,您可以将您的行写回到文件中

编辑:

关于您的评论,也许是这样的:

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
Run Code Online (Sandbox Code Playgroud)

编辑:

由于您的文件均匀地分为四部分,因此可以使用以下方法:

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.
Run Code Online (Sandbox Code Playgroud)


FMc*_*FMc 5

另一种方法:

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
Run Code Online (Sandbox Code Playgroud)

同样相关的是模块中的grouper() 配方itertools。在这种情况下,您需要None先过滤掉这些值,然后再将它们传递给调用者。