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

时间:2017-10-26 22:07:39

标签: 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)

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

P.S。我使用Linux机器

2 个答案:

答案 0 :(得分:3)

最快的路线是使用shell的stdout重定向操作符(>)将输出发送到文件:

$ python your_script.py > your_new_file.txt

追加该文件,请使用append运算符,而不是覆盖恰好存在的任何文件:

$ python your_script.py >> your_appended_file.txt

如果您需要纯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 )
        ...

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

答案 1 :(得分:2)

我试过下面的一个,我希望这有帮助,请注意该文件将在你的python文件夹目录中创建。您可以将其用作参考并根据您的要求进行创建。

f = open('workfile', 'w')
for i in range(3):
    f.write('This is a test\n')
    intvalue =0
    s = str(intvalue)
    f.write(s)

f.close()