文件没有合并:python

时间:2014-03-26 04:13:37

标签: python

我想将两个文件的内容合并为一个新的输出文件。

我已经阅读了有关合并文件内容的其他主题,我尝试了几个选项,但我只在输出中获得了一个文件。这是我尝试过的代码之一,我看不出它有什么问题。

我只在输出中得到一个文件,即使我在列表中切换file1和file2的位置,我仍然只在输出中得到file1。

这是我的代码:

filenames = ['file1','file2']
with open('output.data', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            outfile.write(infile.read())

我该怎么做?

我的整个代码导致合并到这两个文件

source1 = open('A','r')
output = open('file1','w')
output.write(',yes.\n'.join(','.join(line) for line in source1.read().split('\n')))

source1 = open('B', 'r')
output = open('file2','w')
output.write(',no.\n'.join(','.join(line) for line in source2.read().split('\n')))

filenames = ['file1','file2']
with open('output.data', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            outfile.write(infile.read())

3 个答案:

答案 0 :(得分:1)

output重新绑定到新文件时,第一个文件正在关闭/刷新。这是CPython的行为,但依靠它是不好的

使用上下文管理器确保在尝试读取文件之前正确刷新(和关闭)文件

with open('A','r') as source1, open('file1','w') as output:
    output.write(',yes.\n'.join(','.join(line) for line in source1.read().split('\n')))

with open('B','r') as source2, open('file2','w') as output:
    output.write(',no.\n'.join(','.join(line) for line in source2.read().split('\n')))

filenames = ['file1','file2']
with open('output.data', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            print("Reading from: " + fname)
            data = infile.read()
            print(len(data))
            outfile.write(data)

前两个街区有一些重复。也许你可以在那里使用一个功能。

答案 1 :(得分:1)

编辑后,你的错误就在哪里。您需要在写入之后关闭(或刷新)文件,然后才能通过相同的代码读取它。

source1 = open('A','r')
output = open('file1','w')
output.write(',yes.\n'.join(','.join(line) for line in source1.read().split('\n')))
output.close()

source2 = open('B', 'r')
output = open('file2','w')
output.write(',no.\n'.join(','.join(line) for line in source2.read().split('\n')))
output.close()

filenames = ['file1','file2']
with open('output.data', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            outfile.write(infile.read())

第一个文件可用的原因是您通过重新分配变量file1来保留output的文件描述符来删除对file2文件描述符的引用,并且它将由Python自动关闭。

正如@gnibbler建议的那样,最好使用with语句来避免将来出现这种问题。您应该将source1source2output括在with语句中,就像您在上一部分中所做的那样。

答案 2 :(得分:1)

您可以将读取和写入合并为一个语句(如果您不需要中间文件);这也将解决你的结束问题:

with open('A') as a, open('B') as b, open('out.txt','w') as out:
   for line in a:
       out.write(',yes.\n'.join(','.join(line)))
   for line in b:
       out.write(',no.\n'.join(','.join(line)))