- Python Features
- Python Installation
- PyCharm Configuration
- Python Variables
- Python Data Types
- Python If Else
- Python Loops
- Python Strings
- Python Lists
- Python Tuples
- Python List Vs Tuple
- Python Sets
- Python Dictionary
- Python Functions
- Python Files I/O
- Read Write Excel
- Read Write JSON
- Read Write CSV
- Python OS Module
- Python Exceptions
- Python Datetime
- Python Collection Module
- Python Sys Module
- Python Decorator
- Python Generators
- Python OOPS
- Python Numpy Module
- Python Pandas Module
- Python Sqlite Module
Introduction
File handling in Python is a fundamental concept that allows you to read from and write to files on your computer.
Opening a file: To open a file, you can use the built-in open() function. It takes two arguments: the file path (including the file name) and the mode in which you want to open the file.
Different Modes to Open File.
In Python, file handling modes are used to specify the intended operation when opening a file. Each mode determines whether the file should be opened for reading, writing, appending, or exclusive creation. Here are the different modes in Python file handling without plagiarism:
- Read Mode (‘r’):
This is the default mode when opening a file. It allows you to read the contents of an existing file. If the file does not exist, a `FileNotFoundError` will be raised.
# Example:
file = open('file.txt', 'r')
content = file.read()
file.close()
- Write Mode (‘w’):
Write mode opens a file for writing. If the file exists, it truncates (empties) the file before writing to it. If the file does not exist, a new file is created. Be cautious because opening a file in write mode will erase its previous contents.
# Example:
file = open('file.txt', 'w')
file.write('Hello, world!n')
file.close()
- Append Mode (‘a’):
Append mode opens a file for appending new data at the end. If the file exists, the data will be added to the existing content. If the file does not exist, a new file is created.
# Example:
file = open('file.txt', 'a')
file.write('New linen')
file.close()
- Exclusive Creation Mode (‘x’):
Exclusive creation mode opens a file for writing but only if the file does not already exist. If the file exists, a `FileExistsError` is raised.
# Example:
try:
file = open('file.txt', 'x')
file.write('New file created')
file.close()
except FileExistsError:
print("File already exists!")
- Binary Mode (‘b’):
Binary mode is an optional flag that can be added to any of the above modes. It is used when working with binary files, such as images or audio files. This mode ensures proper handling of binary data.
# Example:
# Opens a binary file in read mode
file = open('image.jpg', 'rb')
content = file.read()
file.close()
Context Manager
A context manager in Python to open a file ensures that the file is automatically closed after use — even if an error occurs. This prevents resource leaks and makes the code cleaner.
It’s important to note that using the `with` statement is recommended when working with files, as it automatically takes care of closing the file, even if an exception occurs. Here’s an example using the `with` statement:
# Perform operations on the file
with open('file.txt', 'r') as file:
content = file.read()
print(content)
Different methods in Python File IO
- `read()` method:
The `read()` method is used to read the entire contents of a file as a single string. Here’s an example:
with open('file.txt', 'r') as file:
content = file.read()
print(content)
- `readline()` method:
The `readline()` method is used to read a single line from a file. Here’s an example:
with open('file.txt', 'r') as file:
line = file.readline()
print(line)
- `readlines()` method:
The `readlines()` method reads all the lines of a file and returns them as a list of strings. Here’s an example:
with open('file.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line)
- `write()` method:
The `write()` method is used to write a string to a file. Here’s an example:
with open('file.txt', 'w') as file:
file.write('Hello, world!n')
- `writelines()` method:
The `writelines()` method is used to write a list of strings to a file, where each string represents a line. Here’s an example:
lines = ['Line 1n', 'Line 2n', 'Line 3n']
with open('file.txt', 'w') as file:
file.writelines(lines)
- `seek()` method:
The `seek()` method is used to change the file’s current position to the given offset. Here’s an example:
with open('file.txt', 'r') as file:
# Moves the file pointer to the 6th character
file.seek(5)
content = file.read()
print(content)
- `tell()` method:
The `tell()` method is used to return the current position of the file pointer. Here’s an example:
with open('file.txt', 'r') as file:
content = file.read(10) # Reads the first 10 characters
position = file.tell() # Retrieves the current position
print(position)