write output to a file in python code example
Example 1: python save output to file
with open("output.txt", "a") as f:
print("Hello StackOverflow!", file=f)
print("I have a question.", file=f)
Example 2: python file handling
with open('filename', 'a') as f:
f.write(var1)
f.write('data')
f.close()
with open('filename', 'r') as f:
with open('filename', 'x') as f:
with open('filename', 't') as f:
with open('filename', 'b') as f:
with open('filename', 'w') as f:
with open('filename', '+') as f:
Example 3: print output python to file
print("Hello stackoverflow!", file=open("output.txt", "a"))
print("I have a question.", file=open("output.txt", "a"))
Example 4: python open and read file with
with open('pagehead.section.htm','r') as f:
output = f.read()