how to print a file in python code example
Example 1: code for showing contents of a file and printing it in python
import os
with open("filename", "r+") as file:
content = file.readline()
while(content!=""):
print(content)
content = file.readline()
file.close
Example 2: 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 3: 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 4: open file python
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 5: python how to make a file to write to
file_object = open("filename", "mode")
file_object.write("Data to be written")
file_object.close()
file_object = open("/path/to/my_filename.txt", "w")
file_object.write("Line of text to write")
file_object.close()
Example 6: python print file
import sys
print("Hello Python!", file=open('output.txt','a'))
print("Not written")
sys.stdout = open('output.txt','wt')
print("Hello Python!")