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

标签 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

这种情况持续了数百次。

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

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

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/

相关文章:

camera - 移动相机关闭后,Three.js buffergeometry 消失

python - 我如何打印/返回文件中的行数

python - 如何使 Python 库在 PYTHONPATH 中可访问?

python - 用于记录继承另一个类的类的 PEP8 约定是什么?

python - 在实现约束的同时,是否有更有效的方法来暴力破解随机分布?

eclipse - 加快 PDE 编辑-编译-调试周期

forms - Delphi:显示和填写法律表格或报告

java - 编辑 JFrame 中的现有图像

python - 如何正确使用 tkinter create_line() 坐标

python - matplotlib:将颜色分配给半径