【问题标题】:Append is giving different results than writeAppend 给出的结果与 write 不同
【发布时间】:2017-06-12 18:10:14
【问题描述】:

我正在尝试将多个二进制文件转换为一个 CSV 文件。如果我对文件使用'w'#write,我的代码就可以工作,但是每次新的迭代都会覆盖最后一个。但是,当我使用 'a' #add 到文件时,我的结果值与使用 'w' 时不同(并且不正确)。有没有办法在不使用追加的情况下将我的结果放入一个文件而不覆盖以前的结果?

这是我的代码:

import os
import numpy as np

fileLib1 = ('/path1/')
ref = ('/path2/ref.csv')

for file in os.scandir(fileLib1):
    with open(file,'rb') as f:
        text = list(np.fromfile(f,dtype=np.float32))
    with open(ref,'a') as conv:   #problem, 'a' vs 'w'
        for n in text:
            conv.write('%s,\n' %n)

【问题讨论】:

  • 使用open(file, 'ab') 代替编写二进制文件。
  • 'ab' 给了我问题,'内核死了,重新启动'。到目前为止,“rb”似乎对我有用。

标签: python python-3.x io


【解决方案1】:

我不明白你为什么在每次迭代时打开和关闭目标文件:只需在程序的开头使用w 打开文件,然后在最后关闭它:

import os
import numpy as np

fileLib1 = ('/path1/')
ref = ('/path2/ref.csv')

with open(ref,'w') as conv: # open the target file at the beginning
    for file in os.scandir(fileLib1):
        with open(file,'rb') as f:
            text = list(np.fromfile(f,dtype=np.float32))
        for n in text:
            conv.write('%s,\n' %n)

这也可能会稍微提高程序的性能,因为打开/关闭/...文件通常是操作系统操作,因此可以说不是免费的。

【讨论】:

  • 感谢您的建议,但这样安排给了我同样的问题,由于某种原因,我生成的文件的值与应有的值不同。我不明白为什么会这样,但是,确实如此。
  • @Appelynn:在这种情况下,它不能是飞行模式。您确定它不是包含奇怪结果的 numpy 文件之一。请注意,最初只保存最后一个 numpy 文件。
  • 原来我有一个隐藏文件让我很困惑,谢谢你的帮助。
猜你喜欢
  • 2019-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多