How to view the contents of a file in Python?
In Python, you can use the open() function to open a file and then use the read() method to read the file’s contents.
Here is a simple example:
file = open('file.txt', 'r')
content = file.read()
print(content)
file.close()
In this example, we open the file named file.txt and use the read() method to read the contents of the file. Next, we print the contents of the file using the print() function.
Please note that after using the file, you need to close it using the close() method to release resources.
Another common method is to use the with statement to automatically close the file. For example:
with open('file.txt', 'r') as file:
content = file.read()
print(content)
Using the “with” statement ensures that the file is automatically closed after it is finished being used, without the need to manually call the “close()” method.