0% found this document useful (0 votes)
2 views12 pages

07 Python File Handling

File handling in Python enables reading from and writing to files using built-in functions like open(), read(), and write(). It supports various file modes (e.g., read, write, append) and emphasizes best practices such as using the 'with' statement for automatic file closure. Additionally, Python provides methods for checking file existence, deleting files, and manipulating file pointers for efficient data access.

Uploaded by

rashidulislam73e
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views12 pages

07 Python File Handling

File handling in Python enables reading from and writing to files using built-in functions like open(), read(), and write(). It supports various file modes (e.g., read, write, append) and emphasizes best practices such as using the 'with' statement for automatic file closure. Additionally, Python provides methods for checking file existence, deleting files, and manipulating file pointers for efficient data access.

Uploaded by

rashidulislam73e
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python File Handling

File Handling in Python

• File handling in Python allows reading


from and writing to files. Python
provides built-in functions to perform
file operations such as opening,
reading, writing, and closing files.
• It involves managing the data flow
between the program and the file
system on the storage device,
ensuring that data is handled safely
and efficiently.
Opening a File
• To work with a file, it must be opened using the open() function:
file = open("[Link]", mode)
"[Link]" → Name of the file
mode → Specifies the file operation mode
Mode Description
• File Modes: Read mode (default). Opens the file for reading. Raises
'r'
an error if the file doesn’t exist.
Write mode. Creates a new file or overwrites an existing
'w'
file.
Append mode. Adds data to an existing file. Creates a
'a'
new file if it doesn’t exist.
Exclusive creation mode. Creates a new file; raises an
'x'
error if the file already exists.

'b' Binary mode (use with other modes, e.g., 'rb', 'wb').

't' Text mode (default). Reads and writes in text format.


Reading a File
• Reading entire file:

file = open("[Link]", "r")


content = [Link]()
print(content)
[Link]()

• Reading line-by-line

file = open("[Link]", "r")


for line in file:
print([Link]()) # strip() removes extra newline characters
[Link]()

• Reading a Specific Number of Characters

file = open("[Link]", "r")


content = [Link](10) # Reads first 10 characters
print(content)
[Link]()
Writing to a File
• Writing with 'w' Mode
file = open("[Link]", "w")
[Link]("Hello, World!\n")
[Link]("This is a new file.")
[Link]()
# This will overwrite the file if it already exists.

• Appending with 'a' Mode


file = open("[Link]", "a")
[Link]("\nAppending new data.")
[Link]()
Handling Exceptions When Closing a File
• It is important to handle exceptions to ensure that files are
closed properly, even if an error occurs during file operations.

try:
file = open(“[Link]", "r")
content = [Link]()
print(content)
finally:
[Link]()
Using with Statement (Best Practice)
• Using with open(), Python automatically closes the file after the
operation:
with open("[Link]", "r") as file:
content = [Link]()
print(content)
# No need to call [Link]() manually.

with open() is the preferred way to handle files in Python.


It automatically closes the file, preventing resource leaks.
Supports reading, writing, appending, and binary file operations.
Useful for handling multiple files efficiently.
Working with Binary Files
• Binary files store data in raw binary format rather than as text.
These files include images, videos, audio files, executable
programs, and serialized objects. Unlike text files, binary files are
not human-readable and require special handling.

with open("[Link]", "rb") as file:


binary_data = [Link]()

with open("[Link]", "wb") as file:


[Link](binary_data)
Checking if a File Exists (Using os Module)

import os
if [Link]("[Link]"):
print("File exists")
else:
print("File does not exist")

Deleting a File

import os
[Link]("[Link]")
File Pointer Methods
• A file pointer is a cursor that keeps track of the current position while
reading or writing a file.
• Python provides methods to manipulate the file pointer, which is especially
useful for random access to file content.
• File Pointer Positioning
When you open a file, the file pointer is initially at position 0 (beginning of
the file). As you read or write, the pointer moves forward.
• tell() – Get Current File Pointer Position
• seek() – Move File Pointer to a Specific Position
• Syntax: [Link](offset, whence)
• offset → Number of bytes to move.
• whence → Reference point for movement (default is 0 - beginning).
file = open("[Link]", "r")
print([Link]()) # Shows current position using tell() mthod
[Link](5) # Moves to the 5th character using seek() method
print([Link]()) # Reads from the new position
[Link]()

# Move Pointer Relative to Current Position (whence=1)


with open("[Link]", "r") as file:
[Link](5) # Read first 5 characters
print([Link]()) # Output: 5
[Link](3, 1) # Move pointer 3 characters ahead from current position
print([Link]()) # Output: 8 (5+3)

tell() gets the current file pointer position.


seek() moves the file pointer to a specific position.
seek(0,2) moves the pointer to end of file.
seek(0,0) resets the pointer to the beginning.
Works with both text and binary files.
Advantages of File Handling in Python
• Versatility : File handling in Python allows us to perform a wide range of
operations, such as creating, reading, writing, appending, renaming
and deleting files.
• Flexibility : File handling in Python is highly flexible, as it allows us to
work with different file types (e.g. text files, binary files, CSV files , etc.)
and to perform different operations on files (e.g. read, write, append,
etc.).
• User – friendly : Python provides a user-friendly interface for file
handling, making it easy to create, read and manipulate files.
• Cross-platform : Python file-handling functions work across different
platforms (e.g. Windows, Mac, Linux), allowing for seamless integration
and compatibility.

You might also like