Python Files
Categories:
less than a minute
This code reads the contents of a text file named file.txt
using the open()
function with the mode rt
(read text) and the encoding utf-8
, and then prints each line of the file to the console using a for loop.
The open()
function returns a file object that can be used to read or write to the file. The for
loop iterates over the lines of the file, and the print()
function is used to print each line to the console. The end=''
parameter is used to prevent print()
from adding a newline character at the end of each line.
Finally, the close()
method is called on the file object to close the file and release any system resources associated with it.
Echo the content of a file to the console
f = open('path/to/file.txt', 'rt' encoding='utf-8')
for line in f:
print(line, end='')
f.close
Feedback
Was this page helpful?
Glad to hear it!
Sorry to hear that.