Python print to a file: Using the file keyword argument

Python print to a file: Using the file keyword argument

Normally, “print” in Python writes to stdout. Write elsewhere with the “file” keyword argument:

f1 = open('file1.txt', 'w')
print('hi, stdout')  # prints: hi, stdout
print('hi, file1', file=f1)  # nothing appears
f1.close()
print(open('file1.txt').read())  # we see: hi, file1