【问题标题】:np.savetxt not appending even when file is still open即使文件仍然打开,np.savetxt 也不会附加
【发布时间】:2020-09-18 12:12:41
【问题描述】:

编辑!!! 最后,我能够使用我想要的 while 循环来编写它,并在追加时保存到正确的输出文件夹。

解决办法:

tempfilename=keyname+'_trimmed.fastq'
TempSavelocation="./fastqs/"+tempfilename
f=open(TempSavelocation,'ab')
icounter=0
while icounter < len(tempid): 
    with open(TempSavelocation,'ab') as f:
    # Creating the type of a structure                  
    structuredArr=np.array([tempid[icounter],tempseq[icounter],"+", tempqc[icounter]])
    np.savetxt(f, structuredArr, fmt=['%s'])  
    icounter=icounter+1 
f.close()

这给了我正确的输出,我也尝试了 for 循环,但有一段时间我对我的特定问题最有用。

问题:

问题是,当我运行 npsavetext 时,它无法正常工作,我最初将其作为一个 while 循环(这在我看来是最理想的,循环遍历具有匹配列表的列表并将它们附加到单个文件)

下面是我的代码:

atable=['a','b','b','a','b','b']
f=open(tempfilename,'ab')
f.write(b"\n")
with open(tempfilename,'ab') as f:
    for s in atable: 
        structuredArr=np.array([s,"+"])    
        np.savetxt("./fastqs/"+tempfilename, structuredArr, delimiter=' ', fmt=['%s'])  
f.close()

预期结果如下:

a
+
b
+
b
+
a
+
b
+
b

实际结果是

+
b

理想情况下,我真正想做的是 下面:

icounter=0
    f=open(tempfilename,'ab'
    while icounter < len(tempid): 
        with open(tempfilename,'ab') as f:
            # Creating the type of a structure
          structuredArr=np.array([tempid[icounter],tempseq[icounter],"+",tempqc[icounter]])
            np.savetxt("./fastqs/"+tempfilename, structuredArr, delimiter=' ', fmt=['%s'])  
            f.write("\n")
        icounter=icounter+1 
    f.close()

我认为后者可能由于我的 while 循环而没有附加。

任何帮助都会很棒。

【问题讨论】:

  • 使用打开的文件对象而不是“np.savetxt”中的文件名。
  • @MichaelButscher 我尝试更改为以下内容.... np.savetxt(TempSavelocation,structuredArr, delimiter=' ', fmt=['%s']) ,但仍然没有附加。
  • @MichaelButscher,谢谢,只要我用完整路径保存了我的 TempSavelocation 就可以了

标签: python numpy append


【解决方案1】:

使用with open 时,使用缩进块进行保存。

In [329]: atable=['a','b','b','a','b','b'] 
     ...: with open('abtest.csv','ab') as f: 
     ...:     for s in atable:  
     ...:         structuredArr=np.array([s,"+"])     
     ...:         np.savetxt(f, structuredArr, delimiter=' ', fmt=['%s'])   
     ...:                                                                                
In [330]: cat abtest.csv                                                                 
a
+
b
+
b
+
a
+
b
+
b
+

【讨论】:

    猜你喜欢
    • 2017-04-10
    • 2013-06-08
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    相关资源
    最近更新 更多