如何在不覆盖python中的任何数据的情况下组合两个文件?

时间:2013-10-18 22:04:20

标签: python shell subprocess cat shutil

我需要连接两个文件,一个包含一个数字,另一个包含至少两行数据。我已经尝试过shutil.copyfile(file2,file1)和subprocess.call(“cat”+ file2 +“>>”+ file1,shell = True),两者都给了我相同的结果。具有单个数字的文件包含一个整数和一个换行符(即两个字符),因此当我将两个文件放在一起时,file2的前两个字符将被覆盖而不是仅添加到结尾。如果我使用“cat file2>> file1”通过shell执行此操作,则不会发生这种情况,并且它可以正常工作。

这就是我的意思:

import numpy as np
from subprocess import call

f.open(file1)
f.write('2\n')
np.savetxt(file2,datafile,fmt)
call("cat " + file2 " >> " + file1, shell=True)

所以不要得到:

2
data data data ...
data data data ...

我明白了:

2
ta data data ...
data data data ...

我不知道造成这个问题的原因是什么,但非常令人沮丧。有什么建议吗?

3 个答案:

答案 0 :(得分:1)

您是否尝试先关闭file1

 f.close()
 np.savetxt... Etc

答案 1 :(得分:1)

问题在于你没有冲洗f。 " 2 \ n"当f最终关闭时,cat完成后仍然在文件缓冲区中并覆盖其他数据。但有更好的方法来做到这一点。阅读numpy docs savetxt,您可以传入文件句柄。 Numpy可以使用现有的文件句柄来写入其数据。不需要第二个临时文件。

import numpy as np

with open(file1, "w") as f:
    f.write('2\n')
    np.savetxt(f, datafile, fmt)

答案 2 :(得分:0)

要将file2追加到file1,您可以将'a'文件模式用作@krookik suggested

from shutil import copyfileobj

with open(file1, 'w') as f: # write file1
    f.write('2\n')
# `with`-statement closes the file automatically

# append file2 to file1
with open(file2, 'rb') as input_file, open(file1, 'ab') as output_file:
    copyfileobj(input_file, output_file)

您的代码无法正常工作,因为f.flush()之后f.close() f.write('2\n') cat可能会丢失file1,即'2\n'命令附加到cat {1}},其内容不会从内存刷新到磁盘,{{1}}稍后会写入(当文件在程序出口处隐式关闭时),因此它会覆盖{{1}}写的内容。 / p>