如何在while循环中创建多个输出文件?

时间:2018-03-11 18:02:17

标签: python python-3.x file math

我设法写了一个包含一些数据的文件。但是,无论我做什么,我都只能获得一个输出文件用于代码的最后一次迭代,当我想在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')   

如何做到这一点?

2 个答案:

答案 0 :(得分:3)

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']

答案 1 :(得分:1)

在while循环中创建一个计数器,并在每次希望输出文件更改的迭代中递增它。 根据计数器值选择要使用的文件。