Python Read Files

Python provides several methods to read data from files. Before reading a file, it must be opened in read mode (r). Open a File for Reading Syntax Example Output: read() The read() method reads the entire file content. Example Output: Read Specific Characters You can specify the number of characters to read. Example Output: readline() […]

2 mins read Lesson 20 of 57 35% through track

Python provides several methods to read data from files. Before reading a file, it must be opened in read mode (r).

Open a File for Reading

Syntax

file = open("file_name.txt", "r")

Example

file = open("sample.txt", "r")

print(file.read())

file.close()

Output:

Hello Python
Welcome to File Handling

read()

The read() method reads the entire file content.

Example

file = open("sample.txt", "r")

content = file.read()

print(content)

file.close()

Output:

Hello Python
Welcome to File Handling

Read Specific Characters

You can specify the number of characters to read.

Example

file = open("sample.txt", "r")

print(file.read(5))

file.close()

Output:

Hello

readline()

The readline() method reads one line at a time.

Example

file = open("sample.txt", "r")

print(file.readline())

file.close()

Output:

Hello Python

Read Multiple Lines

Example

file = open("sample.txt", "r")

print(file.readline())
print(file.readline())

file.close()

Output:

Hello Python
Welcome to File Handling

readlines()

The readlines() method reads all lines and returns them as a list.

Example

file = open("sample.txt", "r")

print(file.readlines())

file.close()

Output:

['Hello Python\n', 'Welcome to File Handling']

Loop Through a File

Example

file = open("sample.txt", "r")

for line in file:
    print(line)

file.close()

Output:

Hello Python
Welcome to File Handling

Using with Statement

Using with automatically closes the file after use.

Example

with open("sample.txt", "r") as file:
    print(file.read())

Output:

Hello Python
Welcome to File Handling

Read File Line by Line

Example

with open("sample.txt", "r") as file:
    for line in file:
        print(line.strip())

Output:

Hello Python
Welcome to File Handling

Summary

  • Open a file in read mode using "r".
  • read() reads the entire file.
  • read(n) reads a specific number of characters.
  • readline() reads one line at a time.
  • readlines() returns all lines as a list.
  • Files can be read using loops.
  • The with statement automatically closes the file.
  • Always close files when not using the with statement.