File I/O (Input/Output) is a crucial part of Python for working with files. Python provides a set of built-in functions and methods for file handling. Python perform operations like reading, writing, and manipulating file data.
Use the open()
function to open a file.
Syntax:
open(file, mode)
file = open('example.txt', 'r')
data = file.read()
file.close()
Always close a file after operations to release resources. Use with
statements to handle files safely.
When working with files, you can specify the mode in which the file is opened:
r
: Read mode (default).w
: Write mode (overwrites the file if it exists).x
: Exclusive creation (fails if the file exists).a
: Append mode.b
: Binary mode.t
: Text mode (default).+
: Read and write mode.with
StatementThe with
statement automatically closes the file.
with open('example.txt', 'r') as file:
data = file.read()
print(data)
Always use with
for file operations to ensure proper resource management and avoid file locks.
Python provides several methods for reading files:
read()
Reads the entire file or a specified number of characters.
with open('example.txt', 'r') as file:
content = file.read()
print(content)
readline()
Reads a single line from the file.
with open('example.txt', 'r') as file:
line = file.readline()
print(line)
readlines()
Reads all lines and returns them as a list.
with open('example.txt', 'r') as file:
lines = file.readlines()
print(lines)
Use readlines()
cautiously with large files, as it loads all lines into memory.
For large files, avoid using read()
or readlines()
as they load the entire file into memory. Instead, iterate over the file object.
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
You can write to files using methods like write()
and writelines()
.
write()
Writes a string to the file.
with open('example.txt', 'w') as file:
file.write("Hello, World!")
writelines()
Writes a list of strings to the file.
with open('example.txt', 'w') as file:
file.writelines(["Line 1\n", "Line 2\n"])
When using 'w'
mode, the file content is overwritten. Use 'a'
mode to append data without erasing the existing content.
Use \n
to ensure lines are properly terminated.
Python allows precise control of the file pointer using seek()
and tell()
.
seek(offset, whence)
Moves the file pointer to a specified location.
offset
: Position to move to.whence
: Reference point (0 = start, 1 = current position, 2 = end).with open('example.txt', 'r') as file:
file.seek(5)
content = file.read()
print(content)
tell()
Returns the current position of the file pointer.
with open('example.txt', 'r') as file:
print(file.tell())
Use seek()
and tell()
for precise file pointer control, especially in binary files.
When working with files, specifying the correct file path is crucial. Paths can be absolute or relative.
# Absolute path
with open('/Users/username/Documents/example.txt', 'r') as file:
content = file.read()
# Relative path
with open('example.txt', 'r') as file:
content = file.read()
Ensure file paths are cross-platform compatible by using the os
or pathlib
modules.
File operations can fail due to reasons like file not found, permission errors, or file locks. Python provides robust exception handling mechanisms to manage such cases.
try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("The file does not exist.")
except PermissionError:
print("Permission denied.")
except Exception as e:
print(f"An error occurred: {e}")
Always handle exceptions to prevent crashes during file operations.
flush()
MethodFlushes the internal buffer to the file.
with open('example.txt', 'w') as file:
file.write("Temporary data")
file.flush()
Use the os
module to check if a file exists.
import os
if os.path.exists('example.txt'):
print("File exists.")
import os
os.remove('example.txt')
Always check if the file exists before attempting to delete it to avoid errors.
project/ ├── example.txt ├── read_file.py ├── write_file.py └── position_demo.py
Objective: Practice reading, writing, and controlling file pointers.
Read File Content:
Example:
def read_file(filename):
with open(filename, 'r') as file:
for line in file:
print(line.strip())
read_file('example.txt')
Write File Content:
Example:
def write_to_file(filename, content):
with open(filename, 'w') as file:
file.write(content)
write_to_file('example.txt', "This is a test.")
File Positioning:
tell()
and seek()
.Example:
with open('example.txt', 'r') as file:
print(file.tell())
file.seek(5)
print(file.read())
Exception Handling:
FileNotFoundError
gracefully.Example:
try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("The file does not exist.")
Organize your file handling scripts and data files systematically for easier maintenance.
File I/O in Python is powerful and flexible. Mastering these operations is essential for any developer working with data or external resources.