To read a text file in Python, you can follow these steps:
- Open the text file using the built-in
open()function, which takes the file name as a parameter and returns a file object.
- Read the contents of the file using one of the methods available on the file object.
- Close the file using the
close()method to free up system resources.
Here’s an example code snippet that demonstrates how to read a text file in Python:
# Open the file for reading file = open("example.txt", "r") # Read the contents of the file contents = file.read() # Print the contents of the file print(contents) # Close the file file.close()
In this example, we first use the
open() function to open the file “example.txt” for reading (“r” mode). Then we read the contents of the file using the
read() method and store it in the variable
contents. Finally, we print the contents and close the file using the
Note that it’s good practice to use a
with statement when working with files, which automatically closes the file after you’re done with it. Here’s an example:
with open("example.txt", "r") as file: contents = file.read() print(contents)
This will automatically close the file when the
with block is exited, even if an exception is raised.