Reading Files in Python
To read a file in Python, you use the open()
function with the "r"
mode. Python provides several methods for reading files, including read()
, readline()
, and readlines()
.
Reading the Entire File:
The read()
method reads the entire file into a single string:
Python
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
Reading Line by Line:
The readline()
method reads one line at a time:
Python
file = open("example.txt", "r")
line = file.readline()
while line:
print(line, end="") # "end" avoids adding extra newline
line = file.readline()
file.close()
Reading All Lines into a List:
The readlines()
method reads all the lines of a file into a list:
Python
file = open("example.txt", "r")
lines = file.readlines()
for line in lines:
print(line, end="")
file.close()
Using the with
Statement:
It's a good practice to use the with
statement when working with files, as it automatically closes the file after the block is executed:
Python
with open("example.txt", "r") as file:
content = file.read()
print(content)
# No need to call file.close()
Reading files is a common task in Python, whether you"re working with text data, logs, or configurations.
Import Links
Here are some useful import links for further reading: