np.savetxt即使在文件仍处于打开状态时也不会追加

2024-06-16 12:49:17 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑!!! 最后,我能够用我想要的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循环

任何帮助都会很好


Tags: abaswithnpopenarraywhilefmt
1条回答
网友
1楼 · 发布于 2024-06-16 12:49:17

使用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
+

相关问题 更多 >