【问题标题】:PYTHON: alternating reading lines from 2 files and appending to a thirdPYTHON:交替读取 2 个文件的行并附加到第三个文件
【发布时间】:2013-04-08 00:11:20
【问题描述】:

我需要编写一个函数 shuffleFiles(afile, bfile, cfile),它从文件 afile 中读取一行,然后从文件 bfile 中读取一行并将这些行分别附加到文件 C。如果文件 afile 或 bfile 已经完全读取然后继续将其他文件中的行附加到文件 C 中。

这是我到目前为止的代码,这些行没有被写入文件,但是如果我将它们换成打印语句,则这些行以正确的顺序打印出来,大多数行之间只有空白 \n .不知道从这里去哪里

def shuffleFiles(afile, bfile, cfile):
  fileA = open(afile, 'r')
  fileB = open(bfile, 'r')
  fileC = open(cfile, 'a')
  fileADone = False
  fileBDone = False
while not fileADone or not fileBDone:
    if not fileADone:
        line = fileA.readline()
        line.rstrip()
        line.strip()
        if line == "" or line == " " or line == "/n":
            fileADone = True
        else:
            fileC.write(str(line))
    if not fileBDone:
        line = fileB.readline()
        line.rstrip()
        line.strip()
        if line == "" or line == " " or line == "/n":
            fileBDOne = True
        else:
            fileC.write(str(line))

fileA.close()
fileB.close()
fileC.close()

【问题讨论】:

  • 你为什么不直接做cat afile bfile >> cfile

标签: python io append readline


【解决方案1】:

这是迭代两个交替可迭代对象(包括文件)的一种方法:

from itertools import chain, izip_longest

fileA = open('file_A.txt')
fileB = open('file_B.txt')

for line in filter(None, chain.from_iterable(izip_longest(fileA, fileB))):
    #Do stuff here.

izip_longest“压缩”两个或多个可迭代对象:

>>> a = [1, 2, 3, 4]
>>> b = ['a', 'b', 'c', 'd', 'e', 'f']
>>> list(izip_longest(a, b))
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (None, 'e'), (None, 'f')]

然后chain.from_iterable 将这些链接成一个长期运行的可迭代对象:

>>> list(chain.from_iterable(izip_longest(a, b)))
[1, 'a', 2, 'b', 3, 'c', 4, 'd', None, 'e', None, 'f']

最后,filterNone 作为第一个参数只返回具有非假值的值。在这种情况下,它用于过滤掉上面列表中的Nones(Nones 将在一个迭代比另一个长时出现),以及过滤掉可能存在于文件。

>>> filter(None, chain.from_iterable(izip_longest(a, b)))
[1, 'a', 2, 'b', 3, 'c', 4, 'd', 'e', 'f']

编辑 - 感谢 Tadeck

将所有这些放在一起,再加上用于打开文件的更 Pythonic 的 with 运算符,我们得到如下结果:

with open('fileA.txt') as fileA, open('fileB.txt') as fileB, open('fileC.txt') as fileC:
    lines = chain.from_iterable(izip_longest(fileA, fileB, fillvalue=''))
    fileC.writelines(filter(None, (line.strip() for line in lines)))

【讨论】:

  • 我只是在写类似的解决方案 :) 您可以考虑添加 with 语句以便很好地打开和关闭文件,还可以使用 writelines()。整个解决方案可能看起来像fileC.writelines(filter(None, chain.from_iterable(izip_longest(a, b))))。给你点赞:)
猜你喜欢
  • 1970-01-01
  • 2022-12-05
  • 1970-01-01
  • 2019-10-04
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多