【问题标题】:How do I combine two files without overwriting any data in python?如何在不覆盖 python 中的任何数据的情况下合并两个文件?
【发布时间】:2013-10-27 21:26:24
【问题描述】:

我需要连接两个文件,一个包含一个数字,另一个包含至少两行数据。我试过 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 ...

我不知道是什么导致了这个问题,但这很令人沮丧。有什么建议吗?

【问题讨论】:

  • 您是否尝试过file1a 模式下简单地将file2 写入file1

标签: python shell subprocess cat shutil


【解决方案1】:

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

import numpy as np

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

【讨论】:

  • 这个。这正是我想要的!我完全放弃了尝试写入整数然后写入数据并认为连接两个文件会更容易!谢谢!如果可以的话,我会投票,但我的声誉还不够高。不过谢谢!
【解决方案2】:

要将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.write('2\n') 之后缺少f.flush()f.close() 作为@beroe suggested 即,当cat 命令附加到file1 时,其内容不会从内存中刷新到磁盘,'2\n' 稍后写入(当文件在程序退出时隐式关闭时),因此它会覆盖cat 写入的内容。

【讨论】:

    【解决方案3】:

    您是否尝试过先关闭file1

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 2010-10-04
      • 1970-01-01
      • 2017-10-19
      相关资源
      最近更新 更多