python print to a file code example
Example 1: 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 2: python file reading
fin = open("NAME.txt", 'r')
body = fin.read().split("\n")
line = fin.readline().strip()
Example 3: python file open
file = open('C:\Users\yourname\files\file.txt','r')
text = file.read()
file = open('C:\Users\yourname\files\file.txt','w')
file.write('This is a typical string')
file.close()
Example 4: print output python to file
print("Hello stackoverflow!", file=open("output.txt", "a"))
print("I have a question.", file=open("output.txt", "a"))
Example 5: with open as file python
>>> with open('workfile') as f:
... read_data = f.read()
>>>
>>> f.closed
True