简体   繁体   English

Python for loop savetxt 每次迭代都在一个文件中

[英]Python for loop savetxt each iteration in one file

I am trying to load two txt files, each file only has one column.我正在尝试加载两个 txt 文件,每个文件只有一列。 Then I do things for each of the file and output two columns/rows for each analysis.然后我为每个文件和 output 为每个分析做两列/行。 I want to save all iterations in the for loop.我想将所有迭代保存在 for 循环中。 In this case the output file would have four columns/rows.在这种情况下,output 文件将有四列/行。 Here is what I got that didn't work这是我得到的不起作用的东西

filelist=["1.txt","2.txt"]
results=[]

for file in filelist:
    a= np.loadtxt(file) 
    do things
    sol = rungekutta4(....)
    Theta = (t4, sol[:, 0])
    savetxt('results.csv', results.append(Theta), delimiter=',')

It is possible to append to a file for each iteration of a loop without numpy .对于没有numpy的循环的每次迭代,可以将 append 写入文件。

filelist=["1.txt","2.txt"]
results=[]

for file in filelist:
    a= np.loadtxt(file) 
    
    ...
    
    #savetxt('results.csv', results.append(Theta), delimiter=',')
    with open('outFilename.csv', 'a') as file: # the 'a' means to append to the end of the file:
        file.write(','.join(results)) # the '[separator]'.join(list) converts a list into a string, with each item separated by [separator]

Just to be clear, the for loop will output the results variable for each iteration.为了清楚起见,for 循环将 output 每次迭代的results变量。

Here is an example of the output:以下是 output 的示例:

a
a,b
a,b,c
a,b,c,d

Note that since the file is being opened over and over again many times, you may find the loop slow for a large number of iterations.请注意,由于文件被反复打开很多次,您可能会发现循环在大量迭代中变慢。

To fix this, you can also open the file at the very beginning of the file, just once.要解决此问题,您还可以在文件的最开头打开文件一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM