Reading from a file

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.
Example
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()

Using the with Statement

Using 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.

Example: Reading and Writing a File

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 Methods and Attributes

Common File Methods
  • 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 Attributes
  • file.name: Name of the file.
  • file.mode: Mode in which the file was opened.
  • file.closed: Boolean indicating if the file is closed.

Example 1: Using 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)
Output
Content using read():
Line 1: Hello, world!
Line 2: This is a test file.
Line 3: Reading the entire file using read().

Example 2: Using 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
Output
Content using readline():
Line 1: Hello, world!
Line 2: This is a test file.
Line 3: Reading the entire file using read().

Example 3: Using 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
Output
Content using readlines():
Line 1: Hello, world!
Line 2: This is a test file.
Line 3: Reading the entire file using read().