Python向fi的现有行追加字符串

2024-04-18 15:52:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有原始文件(原木)如下所示:

title1  title2  title3
o11     o12     o13
o21     o22     o23
o31     o32     o33

和一个目标文件(fd.log公司)如下所示:

^{pr2}$

两个文件的行数相同(可能是数百万行),除了原始文件的标题行。考虑到内存使用情况,我不想把所有行都读入内存。在

在处理完我的脚本之后,我希望得到目标文件(fd.log公司)如下所示:

d11   d12   o13
d21   d22   o23
d31   d32   o33

这意味着我获取了每个原始文件行的最后一个信息并将其附加到相应的目标行。在

从一个文件到另一个文件的行之间的对应只是行的位置,与文件上的信息无关。在

我能做的最接近的脚本是写在下面,它正确地打印了我想要的信息。在

from pathlib import Path

file_from = Path("path-to-origin-file/fo.log").open()
file_to = Path("path-to-destination-file/fd.log").open()

# create an enumerator to iterate over origin file lines
eft = enumerate(file_to)

# skip the first line with titles
next(eft)

for line_counter,line_to in eft:
    print(' '.join([
                line_to.rstrip('\n'), 
                file_from.readline().split()[2]]))

file_from.close()
file_to.close()

Tags: 文件topathfromlog信息目标line
3条回答
with open('text1.txt', 'r') as istr:
    with open('text2.txt', 'r+') as ostr:
        iistr = istr.readlines()
        oostr = ostr.readlines()
        fstr = zip(iistr[1:], oostr)
        output_lines = []
        for iline, oline in fstr:
            # Get rid of the trailing newline (if any).
            output_lines.append(oline.rstrip('\n') + '  ' + iline.split()[2] + '\n')

        ostr.seek(0)
        ostr.writelines(output_lines)
with open('newfile.csv' 'r+b') as f:
    for line_counter,line_to in eft:
        print(' '.join(
            [line_to.rstrip('\n'), 
            file_from.readline().split()[2]])
        )

对于足够小的文件,可以将文件内容准备为列表或字符串,然后将其写入文件,例如:

from pathlib import Path

with Path('in-file').open() as in_file, Path('out-file').open('r+') as out_file:
    lines = []

    for line1, line2 in zip(in_file.readlines()[1:], out_file.readlines()):
        line = '{}   {}\n'.format(line2.rstrip(), line1.split()[-1])
        lines.append(line)

    out_file.seek(0)  # rewind the output file to the beginning
    out_file.writelines(lines)

对于较大的文件,请考虑像stdlib的^{}模块那样使用备份文件。在

相关问题 更多 >