File Objects in Python?

In Python, file handling is a native feature that doesn't require importing any external libraries. The open() function opens a file and returns a file object, which contains methods and attributes for retrieving information or manipulating the opened file.

File Operations Overview

File operations in Python follow a standard sequence ?

  • Opening a file
  • Performing read or write operations
  • Closing the file

Opening a File

The built−in open() function creates a file object. It takes two main arguments: the filename and the mode ?

# Basic syntax
file_obj = open("filename", "mode")

File Modes

The mode parameter specifies how the file should be opened ?

Mode Description
'r' Read mode (default)
'w' Write mode (creates new file or truncates existing)
'a' Append mode (adds to end of file)
'x' Exclusive creation (fails if file exists)
'b' Binary mode
't' Text mode (default)
'+' Read and write mode

Creating and Writing to a File

You can create a new file and write content to it using write mode ?

# Create and write to a file
f = open("sample.txt", "w")
f.write("Hello, Python!\n")
f.write("This is line 2\n")
f.write("This is line 3")
f.close()

print("File created successfully!")
File created successfully!

Reading Files

Reading Entire File Content

# First create a sample file
with open("sample.txt", "w") as f:
    f.write("Hello, Python!\nThis is line 2\nThis is line 3")

# Read entire file
f = open("sample.txt", "r")
content = f.read()
print(content)
f.close()
Hello, Python!
This is line 2
This is line 3

Reading Specific Number of Characters

f = open("sample.txt", "r")
partial_content = f.read(13)
print(partial_content)
f.close()
Hello, Python

Reading Line by Line

f = open("sample.txt", "r")
print("First line:", f.readline().strip())
print("Second line:", f.readline().strip())
print("Third line:", f.readline().strip())
f.close()
First line: Hello, Python!
Second line: This is line 2
Third line: This is line 3

Looping Through File Lines

f = open("sample.txt", "r")
for line_number, line in enumerate(f, 1):
    print(f"Line {line_number}: {line.strip()}")
f.close()
Line 1: Hello, Python!
Line 2: This is line 2
Line 3: This is line 3

File Closing

Always close files after use to free system resources. Attempting to use a closed file raises an error ?

f = open("sample.txt", "r")
f.close()

try:
    f.read()
except ValueError as e:
    print(f"Error: {e}")
Error: I/O operation on closed file.

Using the 'with' Statement

The with statement automatically handles file closing, even if an error occurs ?

# File is automatically closed after the with block
with open("sample.txt", "r") as file:
    content = file.read()
    print("File content:", content)

print("File automatically closed!")
File content: Hello, Python!
This is line 2
This is line 3
File automatically closed!

Conclusion

File objects in Python provide a powerful interface for file operations. Always use the with statement for automatic resource management, or remember to close files manually with close().

Updated on: 2026-03-25T05:43:04+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements