Writing for loop output to a text file in python

10,993

Solution 1

The quickest route is to use the shell's stdout redirection operator (>) to send the output to a file:

$ python your_script.py > your_new_file.txt

To append that file, use the append operator rather than overwriting any file that happens to be there:

$ python your_script.py >> your_appended_file.txt

If you want a pure Python approach, open the file and write to it with .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 )
        ...

(And note here the use of with to open your file, over manually closing your file with f.close. The with statement makes operations like this much safer and puts less burden on you, the programmer to remember small but important details like remember to close the file.)

Solution 2

I tried below one, i hope this helps, please note that the file will be created in your python folder directory. You can use this as a reference and create for your requirements.

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()
Share:
10,993
Mazin
Author by

Mazin

Updated on June 04, 2022

Comments

  • Mazin
    Mazin almost 2 years

    I'm new to Python and I'm using it to write FeniCS FEA model fro heat transfer. However, I was able to write code that does what I wanted it to do except to writing thousands of lines that results from a for loop to a text file.

    I print that output I want to the screen every time that loop is executed but tried the dozens of answers in this site regarding writing to a text file but all failed. here is snippet of the code that contains the for loop

    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)
    

    now I want to write the output of the two print statements up there to text file instead of writing that to the screen.

    P.S. I use a Linux machine

    • Barmar
      Barmar over 6 years
      Open the file and use file.write().
    • Barmar
      Barmar over 6 years
      Please show something that you tried, so we can help you understand what you did wrong instead of just doing it for you.
    • mep
      mep over 6 years
      Give it write ability when opening too. open(“fileName”, “w”). On another note you may be better writing to a csv rather than a text file based on how your print the data