1

I have a line of code which prints a paragraph like this :

print("An Apple a day keeps the doctor away ... ") #paragraph1
.
.
.
print("Two Apples a day keeps two doctors away ... ") #paragraph2
.
.
.
json.dump(someData) #paragraph3

I just want to direct all the paragraphs that have been printed in the console onto a file.

Note:

  • 1) I do not want to use .write() method every single time below the print statement.
  • 2) I want to output to the file using the script itself and not the console. (Not something like this
    How to redirect console output to a text file )

Is there any function that can achieve this? (Write all the paragraphs printed in the console onto a file in one shot?)

2 Answers2

2

divert the stdout to a file

import sys
sys.stdout = open('file', 'w')
print 'hello'
Akshay Apte
  • 1,539
  • 9
  • 24
1

Try storing your paragraphs into string variables. It would look like this

p1 = "An Apple a day keeps the doctor away ... "
p2 = "Two Apples a day keeps two doctor away ... "

print(p1)
print(p2)

with open("output.txt", "w")as output:
    p1and2 = p1 + p2
    output.write(p1and2)

Hope this works

Oqhax
  • 419
  • 1
  • 4
  • 16