0% found this document useful (0 votes)
19 views18 pages

UNIT-III FILES

MC4103 Python programming

Uploaded by

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

UNIT-III FILES

MC4103 Python programming

Uploaded by

Raja shree
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

PYTHON FILES: INTRODUCTION

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.

Why File Handling is Important

 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.

File Object Methods (File Operations)

Python provides built-in functions to handle files, such as:

 open(): Used to open a file and returns a file object.


 close(): Closes an opened file to free up resources.
 read(): Reads the content of a file.
 write(): Writes content to a file.
 seek(): Changes the file's current position.
 tell(): Returns the current position of the file cursor.
 with statement: Ensures proper handling of files by automatically closing the file when
done.
Basic File Operations

1. Opening a file:

file = open("example.txt", "r")

2. Reading a file:

content = file.read()
print(content)

3. Writing to a file:

file = open("example.txt", "w")


file.write("Hello, World!")

4. Appending to a file:

file = open("example.txt", "a")


file.write("\nAppending new content.")

5. Closing a file:

file.close()

6. Using with statement (recommended for better file handling):

with open("example.txt", "r") as file:


content = file.read()
print(content)

Example of Writing and Reading a File

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)

File Paths in Python


A file path is a string that specifies the location of a file in a file system. Python provides various
ways to work with file paths.

Types of File Paths

1. Absolute File Path: Specifies the full path from the root directory.

Example: /home/user/documents/example.txt (Unix/Linux)

Example: C:\Users\Username\Documents\example.txt (Windows)

2. Relative Path Example

If your script is in the same directory as the file, you can use a relative path:

file = open("file.txt", "r")

Working with File Paths in Python

Using the os Module

 os.path.join(): Join path components.


 os.path.dirname(): Get the directory name.
 os.path.basename(): Get the file name.
 os.path.exists(): Check if a file exists.
 os.path.isfile(): Check if a path is a file.
 os.path.isdir(): Check if a path is a directory.

import os

# Join path components


path = os.path.join('documents', 'example.txt')

# Get the directory name


dir_name = os.path.dirname(path)
# Get the file name
file_name = os.path.basename(path)

# Check if a file exists


if os.path.exists(path):
print(f"File '{path}' exists.")

Using the pathlib Module (Python 3.4+)

 Path(): Create a path object.


 path.exists(): Check if a file exists.
 path.is_file(): Check if a path is a file.
 path.is_dir(): Check if a path is a directory.
 path.parent: Get the parent directory.
 path.name: Get the file name.

from pathlib import Path

path = Path('documents/example.txt')

# Check if a file exists


if path.exists():
print(f"File '{path}' exists.")

# Get the parent directory


parent_dir = path.parent

# Get the file name


file_name = path.name

Best Practices:

 Use raw string literals for Windows file paths.


 Use os.path.join() or pathlib to join path components.
 Avoid hardcoding file paths; use variables or configuration files instead.

OPENING AND CLOSING FILES

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 = open("filename.txt", mode)

The open() function has two main parameters:

 File name: The name (or path) of the file you want to open.
 Mode: Specifies the operation you want to perform.

Common modes are:

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.

Examples of Opening Files

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.

Using the with Statement (Recommended)

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.

with open("example.txt", "r") as file:


content = file.read()
print(content)
# No need to call file.close(); it's handled automatically

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.")

# Reading from the file


with open("example.txt", "r") as file:
content = file.read()
print(content)

Summary

1. Opening files is done with open(filename, mode).


2. Closing files can be done with file.close(), but the with statement is a preferred approach
as it automatically handles closing.
3. File modes determine how the file will be used (read, write, append, etc.).
4. Using with for file handling ensures automatic closing and cleaner code.

READING AND WRITING FILES

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:

1. read(): Reads the entire file content.


2. readline(): Reads a single line from the file.
3. readlines(): Reads all lines in a file as a list of strings.

Example of Reading a File

Assume we have a file named example.txt with the following content:

Hello, World!
Welcome to file handling in Python.
This is the third line.

1. Reading the Entire File with read()

with open("example.txt", "r") as file:


content = file.read()
print(content)

2. Reading a File Line by Line with readline()


with open("example.txt", "r") as file:
line = file.readline()
while line:
print(line.strip()) # `strip()` removes newline characters
line = file.readline()

3. Reading All Lines as a List with readlines()


with open("example.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line.strip())

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.

 write(): Writes a string to the file.


 writelines(): Writes a list of strings to the file.
Example of Writing to a File

1. Writing a Single Line with write()


with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a new file created with Python.\n")

Note: Opening a file in "w" mode will overwrite its content if it already exists.

2. Appending to a File with a


with open("example.txt", "a") as file:
file.write("This line is appended.\n")

3. Writing Multiple Lines with writelines()


lines = ["First line.\n", "Second line.\n", "Third line.\n"]
with open("example.txt", "w") as file:
file.writelines(lines)

Reading and Writing Binary Files

For non-text files, such as images or executable files, you can use binary modes ("rb", "wb",
"ab").

Example of Reading and Writing a Binary File


# Reading a binary file
with open("image.jpg", "rb") as file:
data = file.read()

# Writing to a binary file


with open("copy.jpg", "wb") as file:
file.write(data)

Summary of File Modes

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.

Example: Combining Reading and Writing

Here’s a complete example that reads from one file and writes to another:

# Read from an existing file


with open("source.txt", "r") as source_file:
content = source_file.read()

# Write content to a new file


with open("destination.txt", "w") as destination_file:
destination_file.write(content)

Using these functions, we can read from or write to files as needed in our programs!

File Position in Python


In Python, file position refers to the current location in a file where data is being read or written.

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.

with open('myfile.txt', 'r') as file:


current_position = file.tell()
print(current_position)

2. seek() Method:

 Moves the file pointer to a specific position.


 Takes two arguments:
o offset: The number of bytes to move.
o whence: The reference point from which to move the offset:
 0: Beginning of the file
 1: Current position
 2: End of the file

with open('myfile.txt', 'r') as file:


# Move to the 10th byte
file.seek(10)
# Move 5 bytes forward from the current position
file.seek(5, 1)
# Move to the 10th byte from the end of the file
file.seek(-10, 2)

Example: Reading a Specific Part of a File

with open('myfile.txt', 'r') as file:


# Move to the 100th byte
file.seek(100)
# Read the next 20 bytes
data = file.read(20)
print(data)

File Position in Python

In Python, file position refers to the current location in a file where data is being read or written.
File Position Methods
tell()

Returns the current file position.

file = open('example.txt', 'r')


position = file.tell()
print(position)

seek()

Changes the file position to a specified location.

file = open('example.txt', 'r')


file.seek(10) # Move to the 10th byte
Seek Modes

Mode Description

0 Seek from the beginning of the file (default)


Mode Description

1 Seek from the current position

2 Seek from the end of the file

Examples
file = open('example.txt', 'r')

# Seek to the 10th byte from the beginning


file.seek(10, 0)

# Seek 5 bytes forward from the current position


file.seek(5, 1)

# Seek 10 bytes backward from the end


file.seek(-10, 2)

File Position Use Cases

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.

Example of Using seek() and tell()

Here's an example that demonstrates navigating within a file using seek() and tell():

with open("example.txt", "r") as file:


# Read the first 5 characters
print(file.read(5)) # Output first 5 characters

# Get current position


print("Current Position:", file.tell()) # Should output 5

# Move to the beginning of the file


file.seek(0)
print("After seek(0):", file.read(5)) # Output first 5 characters again

# Move 10 bytes from the current position


file.seek(10, 1)
print("After seek(10, 1):", file.read(5)) # Output next 5 characters after moving 10 bytes
ahead
# Move to the end of the file
file.seek(0, 2)
print("Position at end of file:", file.tell())

Using File Positioning to Modify Content

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:

with open("example.txt", "r+") as file:


# Move to a specific position
file.seek(5)
# Overwrite content starting from the 5th byte
file.write("NEW")

Example: Moving the File Pointer and Reading Data

with open("example.txt", "r") as file:


print("Initial position:", file.tell()) # Position at the start (0)

file.read(10) # Read 10 characters


print("After reading 10 characters:", file.tell()) # Position after reading 10 characters

file.seek(0) # Move the pointer back to the beginning of the file


print("After seeking to the beginning:", file.tell())

content = file.read(5) # Read the first 5 characters


print("Content read:", content)
print("Position after reading 5 characters:", file.tell()) # Position after reading 5 characters

Exceptions : Errors and Exceptions in Python


Python provides a robust exception handling mechanism to handle runtime errors.
Types of Errors

1. Syntax Errors: Invalid Python syntax.


2. Runtime Errors: Errors occurring during execution.
3. Logical Errors: Incorrect program logic.
Exception Hierarchy

 BaseException: Base class for all exceptions.


 SystemExit: Raised when sys.exit() is called.
 KeyboardInterrupt: Raised when the user interrupts the program.
 Exception: Base class for most exceptions.

Common Exceptions

 TypeError: Invalid data type.


 ValueError: Invalid value.
 NameError: Unknown variable or function.
 ZeroDivisionError: Division by zero.
 IOError: Input/Output error.
 ImportError: Import failure.

Try-Except Block

try:
# Code that may raise an exception
except ExceptionType:
# Handle the exception

Example: Handling Division by Zero


try:
x=5/0
except ZeroDivisionError:
print("Cannot divide by zero!")
Raising Exceptions

raise ExceptionType("Error message")

Example: Raising a ValueError


def validate_age(age):
if age < 18:
raise ValueError("Age must be 18 or older")

Finally Block

try:
# Code that may raise an exception
except ExceptionType:
# Handle the exception
finally:
# Code to execute regardless of exceptions

Example: Closing a File


try:
file = open('example.txt', 'r')
except IOError:
print("File not found!")
finally:
if 'file' in locals():
file.close()

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

Example: Creating a Custom Exception


class InsufficientBalance(Exception):
def __init__(self, balance):
self.balance = balance
super().__init__(f"Insufficient balance: {balance}")

EXCEPTION HANDLING IN PYTHON

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.

Why Use Exception Handling?

Exception handling is essential for:

1. Making code more resilient and user-friendly.


2. Ensuring resources (like files or network connections) are properly closed even if an error
occurs.
3. Handling unexpected inputs or events without crashing the program.

Basic Syntax of Exception Handling

The basic syntax for handling exceptions is as follows:

try:

# Code that might raise an exception

except ExceptionType:

# Code to execute if a specific exception occurs

else:

# Code to execute if no exception occurs (optional)

finally:

# Code that runs no matter what, even if an exception occurs (optional)

 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.")

Handling Multiple Exceptions

You can catch multiple exceptions in one except block or in separate ones.

Separate except Blocks

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}")

Base Exception Classes

1. Exception: Base class for most exceptions.


2. SystemExit: Raised when sys.exit() is called.
3. KeyboardInterrupt: Raised when the user interrupts the program.
Common Exception Classes

1. TypeError: Invalid data type.


2. ValueError: Invalid value.
3. NameError: Unknown variable or function.
4. IOError: Input/Output error.
5. ImportError: Import failure.

Raising Exceptions
raise ExceptionType("Error message")

Example: Raising a ValueError


def validate_age(age):
if age < 18:
raise ValueError("Age must be 18 or older")

Finally Block
try:
# Code that may raise an exception
except ExceptionType:
# Handle the exception
finally:
# Code to execute regardless of exceptions

Example: Closing a File


try:
file = open('example.txt', 'r')
except IOError:
print("File not found!")
finally:
if 'file' in locals():
file.close()

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

Example: Creating a Custom Exception


class InsufficientBalance(Exception):
def __init__(self, balance):
self.balance = balance
super().__init__(f"Insufficient balance: {balance}")

Exception Handling Strategies

1. Fail Fast: Raise exceptions immediately.


2. Fail Safe: Handle exceptions gracefully.
3. Fault Tolerant: Continue execution despite exceptions.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy