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
print("Hello Python!", file=open('output.txt','a'))
print("Not written")
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
with open('filename.txt', 'w') as f:
sys.stdout = f
print('This message will be written to a file.')
sys.stdout = original_stdout
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)