python output to file code example

Example 1: python write to file

file = open(“testfile.txt”,”w”) 
 
file.write(“Hello World”) 
file.write(“This is our new text file”) 
file.write(“and this is another line.”) 
file.write(“Why? Because we can.”) 
 
file.close()

Example 2: python print to file

import sys

# only this print call will write in the file
print("Hello Python!", file=open('output.txt','a'))

# not this one (std output)
print("Not written")

# any further print will be done in the file
sys.stdout = open('output.txt','wt')
print("Hello Python!")

Example 3: python write file

with open("file.txt", "w") as file:
  for line in ["hello", "world"]:
    file.write(line)

Example 4: fastest way to output text file in python + Cout

import sys

print('This message will be displayed on the screen.')

original_stdout = sys.stdout # Save a reference to the original standard output

with open('filename.txt', 'w') as f:
    sys.stdout = f # Change the standard output to the file we created.
    print('This message will be written to a file.')
    sys.stdout = original_stdout # Reset the standard output to its original value

Example 5: python write to file

with open(filename,"w") as f:
  f.write('Hello World')

Example 6: python save output to file

with open("output.txt", "a") as f:
    print("Hello StackOverflow!", file=f)
    print("I have a question.", file=f)