2

我需要编写一个函数 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()
4

1 回答 1

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']

最后,filterwithNone作为第一个参数只返回具有非假值的值。在这种情况下,它用于过滤掉None上面列表中的 s(Nones当一个迭代比另一个长时会发生),以及过滤掉''文件中可能存在的空字符串。

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

编辑 - 感谢 Tadeck

将所有这些放在一起,以及with用于打开文件的更 Pythonic 运算符,我们得到如下内容:

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)))
于 2013-04-08T00:22:24.480 回答