0% found this document useful (0 votes)
4 views26 pages

Python File Handling Basics

Uploaded by

dhanasekarann150
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)
4 views26 pages

Python File Handling Basics

Uploaded by

dhanasekarann150
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

Unit-V

File Handling in Python:

Types of files in python

File handling refers to the process of performing operations on a file


such as creating, opening, reading, writing and closing it, through a
programming interface.

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 in Python


To open a file we can use open() function, which requires file path and
mode as arguments:

# Open the file and read its contents


with open('[Link]', 'r') as file:
This code opens file named [Link].

File Modes in Python


When opening a file, we must specify the mode we want to which
specifies what we want to do with the file.

Here’s a table of the different modes available: Please refer File Mode in
Python for examples of different modes.
Mode Description Behavior

Opens the file for reading. File must


Read-only mode.
r exist; otherwise, it raises an error.

Opens the file for reading binary


Read-only in binary
data. File must exist; otherwise, it
mode.
rb raises an error.

Opens the file for both reading and


Read and write mode. writing. File must exist; otherwise, it
r+ raises an error.

Opens the file for both reading and


Read and write in binary
writing binary data. File must exist;
mode.
rb+ otherwise, it raises an error.

Opens the file for writing. Creates a


Write mode.
w new file or truncates the existing file.

Opens the file for writing binary data.


Write in binary mode. Creates a new file or truncates the
wb existing file.

Opens the file for both writing and


Write and read mode. reading. Creates a new file or
w+ truncates the existing file.

Opens the file for both writing and


Write and read in binary
reading binary data. Creates a new
mode.
wb+ file or truncates the existing file.
Mode Description Behavior

Opens the file for appending data.


Append mode.
a Creates a new file if it doesn't exist.

Opens the file for appending binary


Append in binary mode. data. Creates a new file if it doesn't
ab exist.

Opens the file for appending and


Append and read mode. reading. Creates a new file if it
a+ doesn't exist.

Opens the file for appending and


Append and read in
reading binary data. Creates a new
binary mode.
ab+ file if it doesn't exist.

Exclusive creation Creates a new file. Raises an error if


x mode. the file already exists.

Exclusive creation in Creates a new binary file. Raises an


xb binary mode. error if the file already exists.

Creates a new file for reading and


Exclusive creation with
writing. Raises an error if the file
read and write mode.
x+ exists.

Exclusive creation with Creates a new binary file for reading


read and write in binary and writing. Raises an error if the file
xb+ mode. exists.
● Reading a File
● Writing to a File
● Closing a File
● Handling Exceptions When Closing a File

For this article we are using text file with text:


Helloworld
GeeksforGeeks
123 456
Reading a File

Reading a file can be achieved by [Link]() which reads the entire


content of the file.

After reading the file we can close the file using [Link]() which
closes the file after reading it, which is necessary to free up system
resources.

Example: Reading a File in Read Mode (r)

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


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

Output:
Helloworld
GeeksforGeeks
123 456
Reading a File in Binary Mode (rb)

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


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

Output:
b'Hello world\r\nGeeksforGeeks\r\n123 456'

Writing to a File
Writing to a file is done using [Link]() which writes the specified
string to the file. If the file exists, its content is erased. If it doesn't exist,
a new file is created.

Example: Writing to a File in Write Mode (w)

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


[Link]("Hello, World!")
[Link]()

Writing to a File in Append Mode (a)


It is done using [Link]() which adds the specified string to the end of
the file without erasing its existing content.
Example: For this example, we will use the Python file created in the
previous example.

# Python code to illustrate append() mode


file = open('[Link]', 'a')
[Link]("This will add this line")
[Link]()
Closing a File
Closing a file is essential to ensure that all resources used by the file are
properly released. [Link]() method closes the file and ensures that any
changes made to the file are saved.

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


# Perform file operations
[Link]()

Using with Statement


with statement is used for resource management. It ensures that file is
properly closed after its suite finishes, even if an exception is
raised. with open() as method automatically handles closing the file
once the block of code is exited, even if an error occurs.

This reduces the risk of file corruption and resource leakage.

Program:

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


content = [Link]()
print(content)

Output:
Hello,World!
Appended text.
Example using with statement
Code:
with open("[Link]", mode='r') as f:
# perform file operations
The method shown in the above section is not entirely safe. If some
exception occurs while opening the file, then the code will exit without
closing the file. A safer way is to use a try-finally block while opening
files.
try:
file = open('[Link]',mode='r')
# Perform file handling operations
finally:
[Link] Code:
()
Now, this guarantees that the file will close even if an exception occurs
while opening the file. So, you can use the ‘with’ statement method
instead.

Opening and closing file

Opening and Closing a File in Python


In file handling, we have two types of files one is text files, and
other is binary files. We can open files in python using the open function
open() Function:
This function takes two arguments. First is
the filename along with its complete path, and the other is access
mode. This function returns a file object.
Syntax:
open(filename, mode)

Opening Files:

In Python, you open a file using the open() function. This function
returns a file object, which you can then use to read from or write to the
file.

Basic Syntax

The basic syntax for opening a file is:

file_object=open(filename,mode)

● filename: A string containing the name of the file (and path if necessary)
● mode: A string specifying the mode in which the file should be opened

Examples of Opening Files

1. Opening a file for reading:

f = open('[Link]', 'r')

2. Opening a file for writing:

f = open('new_file.txt', 'w')

3. Opening a file for appending:


f = open('[Link]', 'a')

4. Opening a binary file:

f = open('[Link]', 'rb')

Close() Function:
This function doesn't take any argument, and you can directly call
the close() function using the file object. It can be called multiple times,
but if any operation is performed on the closed file, a "ValueError"
exception is raised.
Syntax:
file.**close()**
You can use the 'with' statement with open also, as it provides
better exception handling and simplifies it by providing some cleanup
tasks. Also, it will automatically close the file, and you don't have to do
it manually.

Closing Files

After you're done with a file, it's important to close it. Closing a
file frees up system resources and ensures that all data is saved properly.

Basic Syntax

To close a file, you call the close() method on the file object:

[Link]()
Reading And Writing Files

Reading files is a fundamental operation in many Python


programs.

Whether you're processing log files, analyzing data, or loading


configuration settings, understanding how to efficiently read files is
crucial.

Basic File Reading Techniques

Reading the Entire File

To read the entire contents of a file into a single string:

with open('[Link]', 'r') as file:


content = [Link]()
print(content)
Use-case: Reading small configuration files or short text documents.

Reading Line by Line

To read a file line by line:

with open('[Link]', 'r') as file:


for line in file:
print([Link]()) # strip() removes leading/trailing whitespace
Use-case: Processing log files or large text files where memory is a
concern.
Reading into a List

To read all lines into a list:

with open('[Link]', 'r') as file:


lines = [Link]()
for line in lines:
print([Link]())
Use-case: When you need to manipulate or analyze the lines out of
order.

Reading and Updating a Database

Reading a file to update a database:

import sqlite3

conn = [Link]('[Link]')
cursor = [Link]()

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


for line in file:
name, email = [Link]().split(',')
[Link]("INSERT INTO users (name, email) VALUES
(?, ?)", (name, email))

[Link]()
[Link]()
Writing To Files In Python

Introduction

Writing to files is a crucial operation in many Python programs.


Whether you're saving data, creating logs, or generating reports,
understanding how to efficiently write to files is essential for a Python
developer.

Basic File Writing Techniques

Writing a String to a File

To write a simple string to a file:

with open('[Link]', 'w') as file:


[Link]("Hello, World!")
Use case: Creating simple text files, writing short messages or status
updates.

Writing Multiple Lines

To write multiple lines to a file:

lines = ["Line 1", "Line 2", "Line 3"]


with open('[Link]', 'w') as file:
for line in lines:
[Link](line + '\n')
Use case: Creating structured text files, writing lists of data.
Appending to a File

To add content to the end of an existing file:

with open('[Link]', 'a') as file:


[Link]("New log entry\n")
Use case: Adding to log files, updating existing documents without
overwriting.

Writing JSON Data

SON stands for JavaScript Object Notation

JSON is a lightweight format for storing and transporting data

JSON is often used when data is sent from a server to a web page

Saving structured data in JSON format:

import json

data = {
"name": "John Doe",
"age": 30,
"city": "New York",
"interests": ["Python", "Data Science", "Machine Learning"]
}

with open('[Link]', 'w') as file:


[Link](data, file, indent=4)
Use case: Storing complex data structures, creating data interchange
files.

Creating a Simple Database

Implementing a basic key-value store:

def save_data(data):
with open('[Link]', 'w') as file:
for key, value in [Link]():
[Link](f"{key}:{value}\n")

def load_data():
data = {}
with open('[Link]', 'r') as file:
for line in file:
key, value = [Link]().split(':')
data[key] = value
return data

# Usage
data = {"user1": "password1", "user2": "password2"}
save_data(data)
loaded_data = load_data()
print(loaded_data)
Use case: Simple data persistence, storing application state.
Python, opening and closing files is straightforward and typically done
using the built-in open() function and the close() method. Here's a
concise explanation with examples:

1. Basic File Handling


# Open a file in read mode
file = open("[Link]", "r")

# Perform operations (e.g., reading content)


content = [Link]()
print(content)

# Close the file


[Link]()

2. Using with Statement (Recommended)


The with statement is preferred because it automatically handles closing
the file, even if an error occurs during file operations.

Copy the code# Open a file in write mode


with open("[Link]", "w") as file:
[Link]("Hello, World!")

# No need to explicitly close the file; it's done automatically.

3. Modes for Opening Files


Here are some common modes you can use with open():

● "r": Read (default mode, file must exist).


● "w": Write (creates a new file or overwrites an existing one).
● "a": Append (adds content to the end of the file).
● "rb", "wb", "ab": Binary modes for reading, writing, or appending.

Example: Reading Line by Line


Copy the codewith open("[Link]", "r") as file:
for line in file:
print([Link]()) # Removes trailing newline characters

Using the with statement ensures your code is clean, safe, and less prone
to errors like forgetting to close the file.

File Position:

In Python, the seek() function is used to move the file cursor to a


specific position inside a file.

This allows you to read or write at any part of the file instead of always
starting from the beginning.

For example, if you want to skip the first 10 characters while reading a
file, you can do:

f = open("[Link]", "r")
[Link](10)
print([Link]())
[Link]()

This will move the file cursor to position 10 and begin reading from
there.
Python, you can work with file positions using
the seek() and tell() methods of file objects. Here's a quick overview:

1. Getting the Current File Position:

● Use the tell() method to find the current position of the file pointer.

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


position = [Link]()
print(f"Current file position: {position}")

2. Changing the File Position

● Use the seek(offset, whence) method to move the file pointer to a


specific position:
o offset: Number of bytes to move.
o whence: Reference point for the offset:
▪ 0: Beginning of the file (default).
▪ 1: Current position.
▪ 2: End of the file.

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


[Link](10) # Move to the 10th byte from the start
print(f"New file position: {[Link]()}")

3. Example: Reading from a Specific Position

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


[Link](5) # Move to the 5th byte
data = [Link](10) # Read the next 10 bytes
print(f"Data read: {data}")
These methods are especially useful when working with large files or
when you need precise control over file reading and writing.

 A file handle or pointer denotes the position from which the


file contents will be read or written. File handle is also called as
file pointer or cursor.
 For example, when you open a file in write mode, the file pointer
is placed at the 0th position, i.e., at the start of the file. However, it
changes (increments) its position as you started writing content
into it.
 Or, when you read a file line by line, the file pointer moves one
line at a time.
 Sometimes we may have to read only a specific portion of the file,
in such cases use the seek() method to move the file pointer to that
position.

For example, use the seek() function to do the file operations like: –

● Read a file from the 10th character.


● Directly jump to the 5th character from the end of the file.
● Add new content to file after a particular position.
Python File seek() Method
xampleGet your own Python Server

Change the current file position to 4, and return the rest of the line:
f = open("[Link]", "r")
[Link](4)
print([Link]())
o! Welcome to [Link]

Renaming And Deleting Files In Python

In Python, you can rename and delete files using built-in functions
from the os module. These operations are important when managing
files within a file system. In this tutorial, we will explore how to perform
these actions step-by-step.

Renaming Files in Python

To rename a file in Python, you can use the [Link]() function.


This function takes two arguments: the current filename and the new
filename.

Syntax:
Following is the basic syntax of the rename() function in Python −
[Link](current_file_name, new_file_name)
Parameters:
Following are the parameters accepted by this function −
● current_file_name − It is the current name of the file you want to
rename.
● new_file_name − It is the new name you want to assign to the file.
Example
Following is an example to rename an existing file "[Link]" to
"[Link]" using the rename() function −
import os

# Current file name


current_name = "[Link]"
# New file name
new_name = "[Link]"

# Rename the file


[Link](current_name, new_name)

print(f"File '{current_name}' renamed to '{new_name}' successfully.")

output:

File '[Link]' renamed to '[Link]' successfully.

Deleting Files in Python:

You can delete a file in Python using the [Link]() function. This
function deletes a file specified by its filename.

Syntax”:
The remove() function in Python −
[Link](file_name)
Parameters:
This function accepts the name of the file as a parameter which needs to
be deleted.
Example:
Following is an example to delete an existing file "file_to_delete.txt"
using the remove() function −
import os

# File to be deleted
file_to_delete = "file_to_delete.txt"

# Delete the file


[Link](file_to_delete)

print(f"File '{file_to_delete}' deleted successfully.")

output:

File 'file_to_delete.txt' deleted successfully.

Directories in Python:

In Python, directories, commonly known as folders in operating


systems, are locations on the filesystem used to store files and other
directories. They serve as a way to group and manage files
hierarchically.

Python provides several modules, primarily os and [Link], along


with shutil, that allows you to perform various operations on directories.

These operations include creating new directories, navigating


through existing directories, listing directory contents, changing the
current working directory, and removing directories.

Checking if a Directory Exists

Before performing operations on a directory, you often need to


check if it exists. We can check if a directory exists or not using
the [Link]() function in Python.

This function accepts a single argument, which is a string


representing a path in the filesystem. This argument can be −
● Relative path − A path relative to the current working directory.
● Absolute path − A complete path starting from the root directory.
Creating a Directory

You create a new directory in Python using


the [Link]() function. This function creates intermediate
directories if they do not exist.

The [Link]() function accepts a "path" you want to create as


an argument. It optionally accepts a "mode" argument that specifies the
permissions o set for the newly created directories. It is an integer,
represented in octal format (e.g., 0o755). If not specified, the default
permissions are used based on your system's umask.
Example
In the following example, we are creating a new directory using
the [Link]() function −
Open Compiler
import os

new_directory = "new_dir.txt"

try:
[Link](new_directory)
print(f"Directory '{new_directory}' created successfully.")
except OSError as e:
print(f"Error: Failed to create directory '{new_directory}'. {e}")

output:
Directory 'new_dir.txt' created successfully.
The mkdir() Method

You can use the mkdir() method of the os module to create directories in
the current directory. You need to supply an argument to this method,
which contains the name of the directory to be created.

The mkdir() method in Python −

[Link]("newdir")
Example
Following is an example to create a directory test in the current directory

Open Compiler
import os

# Create a directory "test"


[Link]("test")
print ("Directory created successfully")

Removing a Directory:

You can remove an empty directory in Python using


the [Link]() method. If the directory contains files or other directories,
you can use [Link]() method to delete it recursively.

Syntax
[Link](directory_path)
# or
[Link](directory_path)
python Program to Merge Mails

Professional communication often involves using emails, which


most people widely use. There are occasions when it becomes necessary
to merge two emails, especially when we require information from both.
Merging emails allows us to consolidate all the information into one
single message, making it easier to access. Let us explore the process of
merging emails.

Part 1, Sending an email!


We’ll be using pywin32, it’s a simple pip install if you don’t already
have it
pip install pywin32

We start by importing the two libraries that we require:


import [Link]
import CSV

The next part is creating the link with Outlook


ol = [Link]('[Link]')

Part 2, Crafting our personalised emails!

Now that we can send one email — we need to personalise what


we’re going to say in each email.

We’ll write a Python function to write the body of the email with
the text we want. In this example, we’ll use the student's grade to
customise part of the message with a piece of wisdom from the tutor.
We utilise Python f strings to make this a very simple task! By
popping a lowercase f before the start of the string for the email_body,
we can use the variable names in curly brackets such as {student_name}
— Python will then replace the placeholder with the actual variable that
is passed in from the function.

Part 3, Emailing our Emails!


Now, we come to the final part, loading our CSV, calling
create_body to personalise our emails and calling send_email to…. send
the email!

We are reading in our names from our CSV using the DictReader
method from the CSV library — this uses the first line of our file as a
header to create an easy-to-use dictionary for accessing the elements
from our CSV.

First, we call create_body to create our personalised email, and


then we pull in the full pathway of our certificate file, before finally
sending our emails. As this is a loop, it will repeat this for every line in
the CSV.( Comma Separated Values)
with open('demo_names.csv', 'r', encoding='utf-8-sig') as emails:
csvreader = [Link](emails)
for row in csvreader:
email_body = create_body(row['student_name'], row['grade'])
certificate_file = "C:\\Users\\Work\\Documents\\python_projects\\"
+ row['certificate_file']
send_email(row['email'], "Your Plate Spinning Class Grade",
certificate_file, email_body)

You might also like