I have a very simple script in python that runs a user defined function (hetero) that joins sequences (strings of text) together over very large files, 2 sequences (rows) at a time. Anyway, As I have it written, it prints out to the screen, but I would like to write all output to a single file.
f = open ("new", "r")
while True:
line1 = f.readline()
line1a = line1.split()
line2 = f.readline()
line2a =line2.split()
if not line2: break
tri="".join ([hetero(b1, b2) for (b1, b2) in zip(line1a[2], line2a[2])])
print line1a[1]+"_"+line1a[0],tri
This simply prints to the terminal the results of the script. So I tried to write the results (from the print command, "line1a[1]+.....") to an another file opened for writing (appended to the end of the script):
out_file = open ("out.txt", "w")
out_file.write(line1a[1]+"_"+line1a[0],tri)
out_file.close()
But of course it does not work. I don't understand why though...Do I need to open the file to write along with the file for reading, so that its outside teh While loop? The thing that is tricky is that the script reads in two lines at a time over the entire file, and prints the ID info and the sequence in a single line, each time -- I want to print all those results to a single file.
This is a simple fix I'm sure, but I don't use python that often and always find the file system i/o difficult to deal with.
:(, you could also use your shell to redirect console output to a file. Instead ofpython my_program.pydo apython my_program.py > out.txt. This way you can keep your print statement as is.