0% found this document useful (0 votes)
3 views21 pages

Module8 - File Operations

Uploaded by

Blossomlove12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views21 pages

Module8 - File Operations

Uploaded by

Blossomlove12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 21

File Operations

Dr. Julius Olaniyan


File
• A file is a named collection of related
information or data that is stored
on a computer's storage device.
• Files are used to store data persistently,
meaning the data remains even after the
program that created it terminates or the
computer is turned off.
• Files can contain a wide range of
information, such as text, images, videos,
audio, program instructions, and more.
Types of Files
• Files are typically organized into a hierarchical file system,
where they are stored within directories (also known as
folders) and subdirectories. Each file is identified by a unique
name within its directory, allowing users and programs to
locate and access specific files.

• Files can be classified into different types based on their contents and purpose.
Some common types of files include:

• Text Files: These contain human-readable text encoded using


a character encoding such as ASCII, UTF-8, or others. Text files
can include documents, configuration files, source code files,
and more.
Types of Files
• Data Files: These contain structured or unstructured
data used by programs for various purposes, such as
databases, spreadsheets, XML files, JSON files, and
more.

• Special Files: These represent system resources or


devices rather than traditional data files. Examples
include device files (e.g., /dev in Unix-like systems),
named pipes, sockets, and symbolic links.
Types of Files
– Binary Files: These contain data in a binary format
that is not intended to be human-readable. Binary
files can store images, videos, executable
programs, compressed data, and other types of
non-textual information.

– Executable Files: These contain machine-readable


instructions that a computer's processor can
execute directly. Executable files include program
executables, scripts, and batch files.
File Operations
• File operations refer to the actions or
tasks performed on files stored on a
computer's storage device.
• These operations allow programs to
read from, write to, modify, and
manage files.
Common File Operations
• Common file operations include:
• Opening a File
• Reading from a File
• Writing to a File
• Appending to a File
• Closing a File
• Renaming and Deleting Files
• Checking File Existence
• Seeking in a File
• Error Handling
Opening a File
• This operation involves creating a connection
between the program and the file on the
storage device, allowing the program to read
from or write to the file.

• Opening a file is typically the first step before


performing any other file operations.
File Modes
• You can open a file using the built-in open()
function. It takes the file path and the mode
as parameters. Modes include:
• 'r': Read mode (default)
• 'w': Write mode (creates a new file or overwrites
existing content)
• 'a': Append mode (appends to the end of the file)
• 'b': Binary mode (for non-text files)
• '+': Read and write mode
read mode
• Read mode is useful when you want to access the
data stored in a file without modifying it.
• It's important to note that attempting to write to
a file opened in read mode will result in an error.:

# Read mode (default)


with open(‘myfile.txt', 'r') as file:
content = file.read()
print(content)
Write mode
• In Python, write mode ('w') is used when you
want to open a file for writing.
• If the file doesn't exist, Python will create it. If the file
does exist, Python will truncate it, meaning it will erase
the contents of the file before writing to it.
# Write mode
with open('myfile.txt', 'w') as file:
file.write("Hello, world!")
– It's important to be cautious when using write mode because
it will overwrite the existing content of the file. If you want to
append to the existing content instead of overwriting it, you
can use append mode ('a').
Append mode
• Append mode ('a') is used when you want to open a file for
appending data to the end of it.
– If the file does not exist, Python will create it. When you write data to a file
opened in append mode, the data will be added to the end of the file without
erasing the existing contents.

# Append mode
with open('myfile.txt', 'a') as file:
file.write("\nThis is appended text.")

– Append mode is useful when you want to add new data to a


file without erasing the existing content.
Binary mode
• Binary mode ('b') is used when you want to read from or write to a file in binary
mode.
• This mode is primarily used for non-text files, such as images, audio files, or binary
data.
• When you open a file in binary mode, it allows you to work with the raw bytes of
the file without any encoding or decoding.

• To open a file for reading in binary mode:


# Binary read mode
with open('myfile.bin', 'rb') as file:
data = file.read()
# Process binary data

• To open a file for writing in binary mode:

# Binary write mode


with open('myfile.bin', 'wb') as file:
# Write binary data
file.write(b'\x00\x01\x02\x03')
Read and Write mode
• Read and write mode ('r+') is used when you want to
open a file for both reading and writing.
• In this mode, you can perform both read and write operations on
the file. If the file does not exist, Python will raise an error.
# Read and write mode
with open('myfile.txt', 'r+') as file:
content = file.read()
file.write("\nThis is additional text.")

it's important to manage the file pointer position carefully


when using this mode to avoid unexpected behavior.
Closing a File
• Closing a File: When you finish working with a file, it's important to
close it using the close() method. This ensures that any resources
associated with the file are properly released.

• Example:
file = open('myfile.txt', 'r')
# Perform operations on the file
file.close()

• Using with statement ensures that the file is properly closed after
its suite finishes, even if an exception is raised during the process.
You don’t need to explicitly close the file.
Renaming and Deleting Files
• You can use the os.rename() function to rename a file and
the os.remove() function to delete a file. Both functions are
in the os module.

• Example (Renaming):
import os
os.rename('oldfile.txt', 'newfile.txt')

• Example (Deleting):

• import os
• os.remove('myfile.txt')
Checking File Existence
• You can check if a file exists using the
os.path.exists() function, which returns True if the
file exists and False otherwise.

• Example:

import os
if os.path.exists('myfile.txt'):
print("File exists")
else:
print("File does not exist")
Seeking in a File
• You can use the seek() method to change the current file position.
This is useful when you want to move the file pointer to a specific
position within the file.
• Example:
file = open('myfile.txt', 'r')
file.seek(10) # Move to the 10th byte in the file

#Move to the fifth line and read it


with open('myfile.txt', 'r') as file:
for _ in range(4): # Skip the first four lines
file.readline()
fifth_line = file.readline() # Read the fifth line
print(fifth_line)

The underscore is just a placeholder variable


File: Error Handling
• When working with files, it's important to handle errors gracefully using
try-except blocks. Common errors include file not found errors, permission
errors, etc.

– Example:
try:
file = open('myfile.txt', 'r')
# Perform operations on the file
except FileNotFoundError:
print("File not found")
except PermissionError:
print("Permission denied")
finally:
if 'file' in locals():
file.close()
Locals()
• In Python, locals() is a built-in function that returns a
dictionary representing the current local symbol table.
This dictionary contains all the variables defined in the
current scope. It's commonly used within functions to
access local variables.
def example_function():
a = 10
b = "Hello"
print(locals())

example_function()

• Output: {'a': 10, 'b': 'Hello'}


THANK YOU

You might also like