Once the file is open, you can read its content using methods like:
read(): Reads the entire file.readline(): Reads one line at a time.readlines(): Reads all lines into a list.file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
with StatementUsing the with statement is a better practice as it ensures the file is properly closed after its suite finishes, even if an exception is raised.
Example:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
This automatically closes the file when the block inside the with statement is exited.
Here’s a complete example demonstrating both reading from and writing to a file:
# Writing to a file
with open('example.txt', 'w') as file:
file.write('Hello, world!\n')
file.write('This is a new line.\n')
# Reading from a file
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
file.close(): Closes the file.file.read(size=-1): Reads up to size bytes from the file (all if -1).file.readline(size=-1): Reads one entire line.file.readlines(): Reads all lines into a list.file.write(string): Writes a string to the file.file.writelines(list): Writes a list of strings to the file.file.name: Name of the file.file.mode: Mode in which the file was opened.file.closed: Boolean indicating if the file is closed.read()The read() method reads the entire content of the file as a single string.
# Write sample data to a file for demonstration purposes
with open('sample.txt', 'w') as file:
file.write("Line 1: Hello, world!\n")
file.write("Line 2: This is a test file.\n")
file.write("Line 3: Reading the entire file using read().\n")
# Read the entire file using read()
with open('sample.txt', 'r') as file:
content = file.read()
print("Content using read():")
print(content)
Content using read():
Line 1: Hello, world!
Line 2: This is a test file.
Line 3: Reading the entire file using read().
readline()The readline() method reads one line at a time from the file.
# Read the file line by line using readline()
with open('sample.txt', 'r') as file:
print("Content using readline():")
while True:
line = file.readline()
if not line:
break
print(line, end='') # end='' to avoid adding extra newlines
Content using readline():
Line 1: Hello, world!
Line 2: This is a test file.
Line 3: Reading the entire file using read().
readlines()The readlines() method reads all lines from the file into a list, where each element is a line from the file.
# Read all lines into a list using readlines()
with open('sample.txt', 'r') as file:
lines = file.readlines()
print("Content using readlines():")
for line in lines:
print(line, end='') # end='' to avoid adding extra newlines
Content using readlines():
Line 1: Hello, world!
Line 2: This is a test file.
Line 3: Reading the entire file using read().