How do you print the contents of a file in Python?

To print the contents of a file, you can utilize the built-in Python functions print() and open() for file operations.

Firstly, use the open() function to open a file and assign it to a variable. For example, to open a text file named file.txt, you can use the following code:

file = open('file.txt', 'r')

Next, use the read() function to read the contents of the file and assign it to a variable. For example, assign the file content to the variable content.

content = file.read()

Finally, use the print() function to display the contents of the file.

print(content)

The complete code is shown below:

file = open('file.txt', 'r')
content = file.read()
print(content)

Ensure to close the file using the close() function after opening it to release resources. For example:

file.close()

However, it is better to use the with statement, which automatically handles the opening and closing of files without the need to manually call the close() function. For example:

with open('file.txt', 'r') as file:
    content = file.read()
    print(content)

Using the “with” statement can help handle file operations more securely.

bannerAds