read a file and print the contents of the file in python

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.py
# Open the file in read mode
with open('example.txt', 'r') as f:

    # Read the contents of the file
    contents = f.read()

    # Print the contents of the file
    print(contents)
184 chars
9 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