UNIT-III FILES
UNIT-III FILES
In Python, files are essential for storing data permanently so that it can be used or retrieved even
after a program has finished executing. This process is called file handling, and it involves
creating, reading, updating, and deleting files.
Data Persistence: Files allow you to store data that persists even after your program
terminates.
Data Sharing: You can share files with others or across different systems.
Data Organization: Files help you organize and manage large amounts of data.
Key Concepts:
File Modes: Determine the purpose of opening a file (e.g., reading, writing, appending).
File Objects: Represent files in Python, providing methods for interacting with files.
File Paths: Specify the location of files in the file system.
File Modes
When opening files, Python offers various modes to specify how you want to work with the file:
r (read): Opens a file for reading (default mode). Raises an error if the file doesn't exist.
w (write): Opens a file for writing (creates a new file or overwrites an existing one).
a (append): Opens a file for appending content at the end (creates a new file if it doesn’t
exist).
r+ (read and write): Opens a file for both reading and writing.
b (binary mode): Used to work with non-text files like images and executables.
1. Opening a file:
2. Reading a file:
content = file.read()
print(content)
3. Writing to a file:
4. Appending to a file:
5. Closing a file:
file.close()
Here's a small program that demonstrates writing to a file and then reading from it:
# Writing to a file
with open("sample.txt", "w") as file:
file.write("This is a sample file.\n")
file.write("It contains multiple lines of text.")
# Reading the file
with open("sample.txt", "r") as file:
content = file.read()
print(content)
1. Absolute File Path: Specifies the full path from the root directory.
If your script is in the same directory as the file, you can use a relative path:
import os
path = Path('documents/example.txt')
Best Practices:
In Python, opening and closing files is essential for managing system resources effectively and
ensuring data integrity.
Opening a File
To work with files in Python, you start by opening them using the open() function. This function
returns a file object, which can then be used to read, write, or modify the file.
File name: The name (or path) of the file you want to open.
Mode: Specifies the operation you want to perform.
o "r": Read (default mode) – Opens a file for reading. Fails if the file doesn’t exist.
o "w": Write – Opens a file for writing. Creates a new file if it doesn’t exist or
truncates the file if it exists.
o "a": Append – Opens a file for appending at the end. Creates a new file if it
doesn’t exist.
o "r+": Read and Write – Opens a file for both reading and writing.
o "b": Binary mode – Used with other modes ("rb", "wb", etc.) to open files in
binary format, useful for non-text files like images or videos.
Reading a File
file = open("example.txt", "r") # Open for reading
content = file.read() # Read the file's content
print(content)
Writing to a File
file = open("example.txt", "w") # Open for writing
file.write("Hello, World!") # Write content to the file
Appending to a File
file = open("example.txt", "a") # Open for appending
file.write("\nAdding more content.") # Add new content to the file
Closing a File
After you are done with a file, you should close it using the close() method. Closing the file
ensures that all data is properly saved and frees up system resources.
file.close()
Forgetting to close a file can lead to memory leaks and file corruption.
A better way to handle files in Python is by using the with statement. It automatically closes the
file when the block of code is exited, even if an exception occurs. This makes code cleaner and
reduces the risk of forgetting to close files.
Complete Example
Here’s a program that writes to a file and then reads from it:
# Writing to a file
with open("example.txt", "w") as file:
file.write("This is an example of using Python to write to a file.\n")
file.write("The with statement ensures the file is closed after we're done.")
Summary
Reading and writing files in Python are fundamental operations that allow programs to persist
data between runs. Python’s built-in file handling functions make these tasks easy.
Reading Files
To read a file in Python, you can use the open() function with reading modes like "r" (text) or
"rb" (binary). Here are some of the common methods for reading files:
Hello, World!
Welcome to file handling in Python.
This is the third line.
Writing Files
To write to a file, you open it in write ("w"), append ("a"), or read-write ("r+") mode. Writing to
a file either creates a new file or overwrites existing content.
Note: Opening a file in "w" mode will overwrite its content if it already exists.
For non-text files, such as images or executable files, you can use binary modes ("rb", "wb",
"ab").
Mode Description
r Read (default); raises an error if file doesn’t exist.
w Write; creates a new file or truncates existing content.
a Append; adds content to the end of the file.
r+ Read and write.
rb Read in binary mode.
wb Write in binary mode.
Mode Description
ab Append in binary mode.
Here’s a complete example that reads from one file and writes to another:
Using these functions, we can read from or write to files as needed in our programs!
you can manipulate the current position within a file using the seek() and tell() methods.
1. tell() Method:
Returns the current position of the file pointer, measured in bytes from the beginning of
the file.
2. seek() Method:
In Python, file position refers to the current location in a file where data is being read or written.
File Position Methods
tell()
seek()
Mode Description
Examples
file = open('example.txt', 'r')
1. Random Access: Seek to specific locations in a file for efficient data retrieval.
2. Data Insertion: Seek to a specific location and insert data without overwriting existing content.
3. Data Deletion: Seek to a specific location and delete data without affecting subsequent content.
Here's an example that demonstrates navigating within a file using seek() and tell():
File positioning is useful when you want to modify specific parts of a file without altering the
entire content. For example, you can open a file in "r+" mode (read and write) and move the
pointer to update specific bytes:
Common Exceptions
Try-Except Block
try:
# Code that may raise an exception
except ExceptionType:
# Handle the exception
Finally Block
try:
# Code that may raise an exception
except ExceptionType:
# Handle the exception
finally:
# Code to execute regardless of exceptions
Best Practices:
Custom Exceptions
class CustomException(Exception):
pass
Exception handling is a mechanism to handle errors that occur during the execution of a
program. It allows you to gracefully handle unexpected situations, prevent program crashes, and
provide informative error messages.
try:
except ExceptionType:
else:
finally:
try: The block where you place code that may raise an exception.
except: Catches and handles a specific exception if it occurs.
else: Executes if no exceptions are raised in the try block.
finally: Executes regardless of whether an exception was raised, making it useful for
cleanup actions.
Example of Basic Exception Handling
try:
number = int(input("Enter a number: "))
result = 10 / number
except ValueError:
print("Invalid input! Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("The result is:", result)
finally:
print("Execution completed.")
You can catch multiple exceptions in one except block or in separate ones.
try:
number = int(input("Enter a number: "))
result = 10 / number
except ValueError:
print("Invalid input!")
except ZeroDivisionError:
print("Cannot divide by zero!")
Combined Exceptions
try:
number = int(input("Enter a number: "))
result = 10 / number
except (ValueError, ZeroDivisionError) as e:
print(f"An error occurred: {e}")
Raising Exceptions
raise ExceptionType("Error message")
Finally Block
try:
# Code that may raise an exception
except ExceptionType:
# Handle the exception
finally:
# Code to execute regardless of exceptions
Best Practices:
1. Always handle specific exceptions.
2. Provide informative error messages.
3. Use try-except blocks judiciously.
4. Avoid bare except clauses.
Custom Exceptions
class CustomException(Exception):
pass