
Python Files I/O
The Python, file I/O (Input/Output) is a fundamental operation that allows you to read from and write to files. Files are a common way to store and retrieve data, and Python provides built-in functions and methods for working with files. Here’s how you can perform file I/O operations in Python:
Opening a File:
To open a file, you can use the open() function. It takes two arguments: the filename and the mode in which you want to open the file (e.g., read, write, append, binary, etc.). The most common modes are:
'r': Read (default mode). Opens the file for reading.'w': Write. Opens the file for writing, truncating (deleting) the file if it already exists.'a': Append. Opens the file for writing, but does not truncate it if it already exists.'b': Binary mode. Used with one of the above modes to read or write binary data (e.g.,'rb','wb').
# Opening a file for reading
file = open('example.txt', 'r')
# Opening a file for writing (creates a new file or overwrites an existing one)
file = open('output.txt', 'w')
# Opening a binary file for reading
file = open('binary_data.bin', 'rb')
Reading from a File:
Once a file is open, you can read its contents using various methods:
read(): Reads the entire file as a single string.readline(): Reads the next line from the file.readlines(): Reads all lines from the file into a list.
# Reading the entire file
contents = file.read()
# Reading lines one by one
line1 = file.readline()
line2 = file.readline()
# Reading all lines into a list
lines = file.readlines()
Writing to a File:
To write data to a file, you can use the write() method:
# Opening a file for writing
file = open('output.txt', 'w')
# Writing data to the file
file.write('Hello, world!\n')
file.write('This is a new line.')
# Closing the file when done
file.close()
Closing a File:
After reading from or writing to a file, it’s essential to close the file using the close() method to free up system resources:
file.close()
Using the with Statement:
A better practice is to use the with statement, also known as a context manager. It ensures that the file is properly closed when you’re done, even if an exception is raised during file operations:
with open('example.txt', 'r') as file:
contents = file.read()
# File is automatically closed when the block is exited
Appending to a File:
To append data to an existing file, you can use the 'a' mode while opening the file:
with open('output.txt', 'a') as file:
file.write('This is appended data.\n')
Iterating Through a File:
You can use a for loop to iterate through the lines of a file:
with open('example.txt', 'r') as file:
for line in file:
print(line)
File I/O is a fundamental part of working with data and files in Python. Always make sure to close files properly and handle exceptions that may occur during file operations to ensure your code is robust and safe.