Skip to content Skip to sidebar Skip to footer

How To Write Python Shell To An Output Text File?

I need to write my Python shell to an output text file. I have some of it written into an output text file but all I need is to now add the number of lines and numbers in each line

Solution 1:

You have closed baconFile in the first open block, but do not open it again in the second open block. Additionally, you never write to baconFile in the second open block, which makes sense considering you've not opened it there, but then you can't expect to have written to it. It seems you simply forgot to add some write statements. Perhaps you confused write with print. Add those write statements in and you should be golden.

baconFile = open(outfile,"wt")
with open("Version2_file.txt", 'r') as f:
    for line in f:                       
        # ... line processing ...
        baconFile.write(...)  # line format info here
    # baconFile.close()  ## <-- move this
with open("Version2_file.txt", 'r') as f:
    content = f.readlines()
    baconFile.write(...)  # number of lines info here
    for i in range(len(content)):
        baconFile.write(...)  # numbers in each line info here
baconFile.close()  # <-- over here

Solution 2:

Here's a useful trick you can use to make print statements send their output to a specified file instead of the screen (i.e. stdout):

from contextlib import contextmanager
import os
import sys


@contextmanager
def redirect_stdout(target_file):
    save_stdout = sys.stdout
    sys.stdout = target_file
    yield
    sys.stdout = save_stdout

# Sample usage
with open('output2.txt', 'wt') as target_file:
    with redirect_stdout(target_file):
        print 'hello world'
        print 'testing', (1, 2, 3)

print 'done'  # Won't be redirected.

Contents of output2.txt file after running the above:

hello world
testing (1, 2, 3)

Post a Comment for "How To Write Python Shell To An Output Text File?"