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

时间:2014-02-03 02:23:00

标签: 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行,但是必须有更好的方法,因为在写出文件时会导致各种各样的问题。我可以用什么作为替代方案?

3 个答案:

答案 0 :(得分:3)

你可以这样做:

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.

答案 1 :(得分:3)

另一种方法:

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

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

答案 2 :(得分:0)

您可以使用.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()