将循环输出写入python中的文本文件

Maz*_*zin 2 python loops text-files

我是 Python 的新手,我正在使用它来编写 FeniCS FEA 模型来进行热传递。但是,除了将 for 循环产生的数千行代码写入文本文件之外,我还能够编写能够完成我想要它做的事情的代码。

每次执行该循环时,我都会将该输出打印到屏幕上,但尝试了该站点中有关写入文本文件的数十个答案,但都失败了。这是包含 for 循环的代码片段

for t in numpy.arange(0, t_end, Dt):
    print 'Time ', t, 'Max_temp ', "%.3E " % T.vector().array().max()

    line_n = int(abs(t / line_time))
    hatch = 0.0002

    if (line_n % 2) == 0 
        f.xx = (0.001 + vel*t - (length*line_n - mis))

    else:
        f.xx = (0.019 - vel*t + (length*line_n - mis))
        f.yy = 0.001 + line_n * hatch

    solve(A, T.vector(), b, 'cg')
    print 'Line#', t,
    timestep += 1
    T0.assign(T)
Run Code Online (Sandbox Code Playgroud)

现在我想将两个打印语句的输出写入文本文件而不是将其写入屏幕。

PS我使用Linux机器

hun*_*eke 5

最快的方法是使用 shell 的 stdout 重定向运算符 ( >) 将输出发送到文件:

$ python your_script.py > your_new_file.txt
Run Code Online (Sandbox Code Playgroud)

附加该文件,请使用 append 运算符而不是覆盖碰巧在那里的任何文件:

$ python your_script.py >> your_appended_file.txt
Run Code Online (Sandbox Code Playgroud)

如果您想要纯 Python 方法,请打开文件并使用以下命令写入.write()

with open('your_new_file.txt', 'w') as f:
    for t in numpy.arange(0, t_end, Dt):
        # attempting to faithfully recreate your print statement
        # but consider using a single format string and .format
        output = ' '.join(('Time ', t, 'Max_temp ', "%.3E " % T.vector().array().max())
        f.write( output )
        ...
Run Code Online (Sandbox Code Playgroud)

(并在此处注意使用with来打开文件,而不是使用 f.close 手动关闭文件。该with语句使这样的操作更加安全并且减轻了您的负担,程序员要记住小但重要的细节,例如记住关闭文件文件。)