To read the contents of a file in Python, you can use the open()
function with the appropriate file mode. Once the file is open, you can read its contents using various methods provided by Python.
Here's an example code block that demonstrates how to read a file and print its contents:
main.py184 chars9 lines
In this code block, the open()
function is used to open the file named example.txt
in read-only mode ('r'
). The contents of the file are then read using the read()
method and stored in the contents
variable. Finally, the contents of the file are printed to the console using the print()
function.
Note that we're using a with
block to open the file. This is a good practice as it automatically closes the file when we're done with it.
gistlibby LogSnag