簡體   English   中英

如何在while循環中創建多個輸出文件?

[英]How can I create multiple output files within a while loop?

我設法寫了一個文件,里面有一些數據。 但是,無論我做什么,當我希望while循環的每次迭代都使用不同名稱的不同輸出文件時,我只能得到一個輸出文件進行代碼的最終迭代(這會更改S0的初始條件):

# zombie apocalypse modeling
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
import pandas as pd
plt.ion()
plt.rcParams['figure.figsize'] = 10, 8

P = 0      # birth rate
d = 0.0001  # natural death percent (per day)
B = 0.0095  # transmission percent  (per day)
G = 0.0001  # resurect percent (per day)
A = 0.0001  # destroy percent  (per day)

# solve the system dy/dt = f(y, t)
def f(y, t):
     Si = y[0]
     Zi = y[1]
     Ri = y[2]
     # the model equations (see Munz et al. 2009)
     f0 = P - B*Si*Zi - d*Si
     f1 = B*Si*Zi + G*Ri - A*Si*Zi
     f2 = d*Si + A*Si*Zi - G*Ri
     return [f0, f1, f2]

# initial conditions
S0 = 500.              # initial population
Z0 = 0                 # initial zombie population
R0 = 0                 # initial death population

while S0 < 600
    S0 += 5

    y0 = [S0, Z0, R0]     # initial condition vector
    t  = np.linspace(0, 5., 1000)         # time grid

    # solve the DEs
    soln = odeint(f, y0, t)
    S = soln[:, 0]
    Z = soln[:, 1]
    R = soln[:, 2]

df = pd.dataframes({S,Z,R]} 
df.to_csv('test.txt', sep='\t')   

如何才能做到這一點?

import os

for k in range(1,10):

    # some loop

    with open("myfile.{}.csv".format(k), "w") as f:  # put a counter inside the files name
        f.write("some data") 
print( os.listdir("./"))

輸出:

['myfile.8.csv', 'myfile.7.csv', 'myfile.6.csv', 'myfile.4.csv',
 'myfile.5.csv', 'main.py', 'myfile.9.csv', 'myfile.1.csv', 
 'myfile.2.csv', 'myfile.3.csv']

我們可以確定文件是否存在,然后自動對其進行遞增:

import os
import datetime


def newName(baseName):
    """Checks if baseName exists, if not inserts a running 
    counter and increments it until file does not exist."""

    n = baseName[:-4]+".{}"+baseName[-4:]  # assumes a len-3 filenameextension like txt
    if not os.path.exists(baseName):
        return baseName

    i = 0
    while os.path.exists( n.format(i)):
        i+=1

    return n.format(i)


with open(newName("myfile.csv"),"w") as f: # newName checks and creates a unique name
    f.write("some data") 

with open(newName("myfile.csv"),"w") as f: # if the file already exists.
    f.write("some data") 

with open(newName("myfile.csv"),"w")  as f:
    f.write("some data") 

print( os.listdir("./"))

輸出:

['myfile.1.csv', 'myfile.csv', 'myfile.0.csv', 'main.py']

在while循環中創建一個計數器,並在每次要更改輸出文件的迭代中將其遞增。 根據計數器值選擇要使用的文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM