File handling is an essential aspect of programming, allowing you to interact with files on your system. Python provides built-in functions and libraries to help you work with files effectively. File handling in Python is straightforward and powerful, enabling you to read from, write to, and manipulate files with ease.
To open a file in Python, use the open() function. This function returns a file object, which you can use to read from or write to the file.
Syntax:
file_object = open(file_name, mode)
Modes:
Example:
# Open a file for reading
file = open('example.txt', 'r')
# Open a file for writing
file = open('example.txt', 'w')
# Open a file for appending
file = open('example.txt', 'a')
# Open a file for reading in binary mode
file = open('example.txt', 'rb')
# Open a file for writing and reading
file = open('example.txt', 'w+')
There are several ways to read from a file in Python:
2.1 read()
Reads the entire file as a single string.
Example:
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
2.2 readline()
Reads one line at a time.
Example:
file = open('example.txt', 'r')
line = file.readline()
while line:
print(line, end='') # The `end=''` argument avoids adding extra newlines
line = file.readline()
file.close()
2.3 readlines()
Reads all lines and returns them as a list of strings.
Example:
file = open('example.txt', 'r')
lines = file.readlines()
for line in lines:
print(line, end='')
file.close()
You can write to a file using the write() and writelines() methods.
3.1 write()
Writes a string to the file.
Example:
file = open('example.txt', 'w')
file.write('Hello, World!\n')
file.write('This is a test.\n')
file.close()
3.2 writelines()
Writes a list of strings to the file.
Example:
file = open('example.txt', 'w')
lines = ['Hello, World!\n', 'This is a test.\n']
file.writelines(lines)
file.close()
Appending data to an existing file can be done using the append mode 'a'.
Example:
file = open('example.txt', 'a')
file.write('Appending this line.\n')
file.close()
Using the with statement for file handling is a best practice in Python. It ensures that the file is properly closed after its suite finishes, even if an exception is raised.
Example:
# Using `with` statement for reading
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# Using `with` statement for writing
with open('example.txt', 'w') as file:
file.write('Hello, World!\n')
file.write('This is a test.\n')
# Using `with` statement for appending
with open('example.txt', 'a') as file:
file.write('Appending this line.\n')