0% found this document useful (0 votes)
10 views51 pages

Python File Handling

The document provides an overview of file handling in Python, detailing the use of the open() function and various file modes such as read, write, and append. It explains the difference between text and binary files, as well as the use of the pickle module for object serialization. Additionally, it covers methods for reading, writing, and manipulating file data, including the use of the with statement for automatic file closure.

Uploaded by

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

Python File Handling

The document provides an overview of file handling in Python, detailing the use of the open() function and various file modes such as read, write, and append. It explains the difference between text and binary files, as well as the use of the pickle module for object serialization. Additionally, it covers methods for reading, writing, and manipulating file data, including the use of the with statement for automatic file closure.

Uploaded by

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

PYTHON FILE HANDLING

BY ARYAN KUMAR
File Handling

The key function for working with files in


Python is the open() function.
The open() function takes two
parameters; filename, and mode.
There are four different methods (modes) for
opening a file:
EXAMPLES:-
"r" - Read - Default value. Opens a file for
reading, error if the file does not exist
"a" - Append - Opens a file for appending,
creates the file if it does not exist
"w" - Write - Opens a file for writing, creates
the file if it does not exist
"x" - Create - Creates the specified file,
returns an error if the file exists
BINARY FILE AND TEXT FILE
In addition you can specify if the file should be
handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
Syntax

To open a file for reading it is enough to specify


the name of the file:
f = open("[Link]")
f = open("[Link]", "rt")
What is a function used for opening files?
load()
run()
open()

Open a File on the Server


Assume we have the following file, located in the same folder
as Python:
To open the file, use the built-
in open() function.
The open() function returns a file object,
which has a read() method for reading the
[Link]
content of the file:
Hello! Welcome to [Link]
This file is for testing purposes.
Good Luck!

f = open("[Link]", "r")
print([Link]())
Example
 f=
Open a fileopen("D:\\myfiles\[Link]",
on a different location: "r")
print([Link]())
Read Only Parts of the File

By default the read() method returns the


whole text, but you can also specify how
many characters you want to return:
Ex f = open("[Link]", "r")
print([Link](5))
Read Lines

You can return one line by using


the readline() method:
f = open("[Link]", "r")
print([Link]())
By calling readline() two times, you can read
the two first lines:
f = open("[Link]", "r")
print([Link]())
print([Link]())
By looping through the lines of the file, you
can read the whole file, line by line:
f = open("[Link]", "r")
for x in f:
print(x)
Close Files

It is a good practice to always close the file


when you are done with it.
f = open("[Link]", "r")
print([Link]())
[Link]()
Q. After opening a file with the open() function,
which method can be used to read the
content?

list()
read()
show()
Write to an Existing File

To write to an existing file, you must add a


parameter to the open() function:
"a" - Append - will append to the end of the
file
"w" - Write - will overwrite any existing
content
Example
Open the file "[Link]" and append content
to the file:
f = open("[Link]", "a")
[Link]("Now the file has more content!")
[Link]()

#open and read the file after the appending:


f = open("[Link]", "r")
print([Link]())
Open the file "[Link]" and
overwrite the content:
f = open("[Link]", "w")
[Link]("Woops! I have deleted the content!")
[Link]()

#open and read the file after the overwriting:


f = open("[Link]", "r")
print([Link]())
Files
In computer science, a file is a collection of
data or information stored on a disk. Files are
used to store programs, documents, media
(like audio, video), and any form of data in an
organized way. Files can be manipulated
using various file operations such as creating,
reading, writing, and deleting.
Types of Files
Text Files
A text file contains human-readable
characters and typically ends with a .txt
extension. The contents of a text file are
written as plain text using character encoding
standards like ASCII or
[Link]: .txt, .html, .xml, .log, .pyC
ommonly used to store:Code or scripts (e.g.,
Python, HTML)
Configuration files
Logs
Tools to open text files: Notepad, TextEdit,
Binary Files
A binary file contains data in binary form (0s and 1s)
and is not meant to be human-readable. These files store
information in a format that can be directly processed by
a machine.
Examples: .exe, .dll, .png, .mp3, .pdf
Commonly used to store:
 Executable files (programs)
 Images, videos, and audio
 Compressed files (e.g., .zip, .rar)
 Application-specific data files (e.g., .dat, .bin)
Tools to open binary files vary depending on their
purpose: image viewers, media players, or specialized
programs.
CSV Files (Comma-Separated Values)
 A CSV file is a type of text file where data is organized in a
tabular format. Each row corresponds to a record, and
columns are separated by commas (or sometimes semicolons,
tabs, etc.).
 CSV files are widely used for exporting and importing data,
especially between databases and spreadsheet programs like
Excel.
 Examples: .csv
 Commonly used to store:
 Spreadsheet data
 Database tables
 Data for analysis
 Tools to open CSV files: Excel, Google Sheets, and text editors.
r+ (Read and Write Mode)
Opens a file for both reading and writing.
The file pointer is placed at the beginning of
the file.
File must exist; if it doesn’t, an error will be
raised.
You can read the file and also modify or write
new data to it.
file = open("[Link]", "r+")
content = [Link]() # Reading the file
[Link]("New content") # Writing to the
file
w (Write Mode)
Opens a file for writing.
Creates a new file if it does not exist.
If the file already exists, it overwrites the
entire content of the file, erasing all existing
data.
file = open("[Link]", "w")
[Link]("This will overwrite the file content.")
w+ (Write and Read Mode)
Opens a file for writing and reading.
Creates a new file if it doesn’t [Link] the file
exists, it overwrites the entire file.
You can write to and also read from the file.
file = open("[Link]", "w+")
[Link]("Overwriting content")
[Link](0) # Move the pointer back to the
start of the file to read
content = [Link]() # Reading what was
written
a (Append Mode)
Opens a file for appending.
Creates a new file if it doesn’t exist.
The file pointer is placed at the end of the
file.
Existing content is not erased; new data will
be added at the end.
file = open("[Link]", "a")
[Link]("Appending new data to the file.")
a+ (Append and Read Mode)
Opens a file for both appending and
reading
.Creates a new file if it doesn’t exist.
The file pointer is at the end of the file for
appending.
You can both append new content and read
the existing content.
file = open("[Link]", "a+")
[Link]("Appending additional data.")
[Link](0) # Move to the start to read
existing content
File mode
How to append data in a file
# Open the file in append mode ('a')
with open("[Link]", "a") as file:
# Data to be appended
new_data = "This is the new content being
appended.\n"

# Append the data to the file


[Link](new_data)

print("Data has been appended to the file.")


With statment
The with statement in Python is widely used
for file handling because it simplifies the
process of working with files and ensures that
files are properly closed after their usage. It
provides a clean and efficient way to open
and close files, eliminating the need to
explicitly call [Link]().
Advantages of Using with for File Handling
Automatic File Closing: When you open a
file with with, the file is automatically closed
when the block of code within the with
statement is done, even if an error occurs
during file [Link] Code: You
don't need to manually manage resources or
worry about forgetting to close the [Link]
Handling: In case of an exception, the file
will still be closed properly
Basic Syntax

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


# Perform file operations here
Writing to a File: writelines()
The writelines() method is used to write a list
of strings to a file. It doesn't add newline
characters (\n) by itself, so if you want to
insert a line break between the list elements,
you need to ensure that each string in the list
ends with \n.
# Writing lines to a file using writelines()
with open("[Link]", "w") as file:
 lines = ["First line\n", "Second line\n",
"Third line\n"]
 [Link](lines)
seek() and tell() Methods
The seek() method moves the file cursor to a
specific byte position. It takes an integer
argument that specifies the position in the file
where the cursor should move
The tell() method returns the current position
of the file cursor, in terms of the number of
bytes from the beginning of the file.
Examples
# Getting the current cursor position using
tell()
with open("[Link]", "r") as file:
position = [Link]()
print(f"Current position: {position}")
Manipulating Data in a Text File
You can manipulate file data by reading the content,
processing it, and then writing the modified content
back to the file.
writelines(): Writes a list of strings to a file.
read(): Reads the entire file content or a specified
number of characters.
readline(): Reads one line at a time from the file.
readlines(): Reads all lines from the file and returns
them as a list.
seek(): Moves the file cursor to a specified byte
position.
tell(): Returns the current position of the file cursor.
Opening a Binary File Using Different File
Modes
rb: Open a file for reading in binary mode.
rb+: Open a file for reading and writing in binary
mode
.wb: Open a file for writing in binary mode. This
mode overwrites the file if it already exists or creates
a new file.
wb+: Open a file for reading and writing in binary
mode, with truncation (overwrites existing content).
ab: Open a file for appending in binary mode. The file
pointer is at the end of the file.
ab+: Open a file for reading and appending in
binary mode.
Binary files allow us to read and write data in a format that is not human-readable, often used for storing structured data like serialized objects. Here’s an overview of working with binary files in Python, including how to use various file modes, the pickle module, and essential file operations.
Opening a Binary File Using Different File Modes
rb: Open a file for reading in binary mode.
rb+: Open a file for reading and writing in binary mode.
wb: Open a file for writing in binary mode. This mode overwrites the file if it already exists or creates a new file.
wb+: Open a file for reading and writing in binary mode, with truncation (overwrites existing content).
ab: Open a file for appending in binary mode. The file pointer is at the end of the file.
ab+: Open a file for reading and appending in binary mode.
Closing a Binary File
After finishing file operations, it’s essential to close the file to free up resources:
python
Copy code
[Link]()
Importing the pickle Module

The pickle module in Python allows for object


serialization, i.e., converting Python objects
into a byte stream, which is ideal for storing
complex objects like lists and dictionaries in
binary files.
import pickle
Writing Data to a Binary File Using
[Link]()
The dump() method serializes a Python object
and writes it to a binary file
data = {"name": "Alice", "age": 25}
with open("[Link]", "wb") as file:
[Link](data, file) # Serialize and write
to the file
Reading Data from a Binary File Using
[Link]()
The load() method deserializes a byte stream
from a binary file back into a Python object.
with open("[Link]", "rb") as file:
data = [Link](file) # Read and
deserialize the object
print(data)
Basic Operations on a Binary File
Create/Write:
To create and write data, open the file in wb or
wb+ mode, then use [Link]() to write
data.
with open("[Link]", "wb") as file:
[Link]({"name": "Bob", "age": 30}, file)
Read:
To read data, open the file in rb mode, then
use [Link]() to retrieve the data.
with open("[Link]", "rb") as file:
data = [Link](file)
print(data)
Append:
Open the file in ab mode and use
[Link]() to add new data to the end of
the file.
with open("[Link]", "ab") as file:
[Link]({"name": "Charlie", "age": 40},
file)
Update/Search:
Since binary files don’t allow random access
in a structured format, updating data
requires reading all records, modifying them
in memory, and writing them back
EXAMPLE
def update_user_age(user_id, new_age):
try:
# Step 1: Read all records from the binary file
with open("[Link]", "rb") as file:
users = [Link](file)

# Step 2: Search for the record by ID and update the age


record_found = False
for user in users:
if user["id"] == user_id:
user["age"] = new_age
record_found = True
break

# Step 3: If the record was found, rewrite the file with updated data
if record_found:
with open("[Link]", "wb") as file:
[Link](users, file)
print(f"User ID {user_id} age updated to {new_age}.")
else:
print(f"No record found with ID {user_id}.")

except (FileNotFoundError, EOFError):


print("The file could not be read or is empty.")

# Usage example:
update_user_age(2, 32)
Step 1: The update_user_age() function
opens [Link] in rb mode and loads the list
of users.
Step 2: It searches for the record with the
specified user_id and, if found, updates the
age.
Step 3: If the record is found, the file is
reopened in wb mode to overwrite it with the
updated list of records. If the record is not
found, a message is printed to inform the
user.
After running the update_user_age(2, 32)
function, you can check if the file reflects the
updated age for the user with ID 2 by loading and
printing the file contents:
with open("[Link]", "rb") as file:
users = [Link](file)
print(users)
OUTPUT
[{'id': 1, 'name': 'Alice', 'age': 25},
{'id': 2, 'name': 'Bob', 'age': 32},
{'id': 3, 'name': 'Charlie', 'age': 35}]
Importing the csv Module
import csv
Writing to a CSV File
There are several methods to write data to a CSV
file: writer(), writerow(), and writerows().
a) Using writer()
The [Link]() method creates a writer object
that lets you write data to a file.
Example:-
with open('[Link]', mode='w', newline='') as
file:
writer = [Link](file)
b) Using writerow()
The writerow() method writes a single row (a
list) to the CSV file.
with open('[Link]', mode='w', newline='')
as file:
writer = [Link](file)
[Link](["Name", "Age", "City"]) #
Write header row
[Link](["Alice", 30, "New York"])
[Link](["Bob", 25, "Los Angeles"])
c) Using writerows()
The writerows() method writes multiple rows (a list of
lists) to the CSV file.
data = [
["Name", "Age", "City"],
["Alice", 30, "New York"],
["Bob", 25, "Los Angeles"],
["Charlie", 35, "Chicago"]
]

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


writer = [Link](file)
[Link](data) # Write multiple rows
Reading from a CSV File
The [Link]() method reads the contents
of a CSV file row by row.
with open('[Link]', mode='r') as file:
reader = [Link](file)
for row in reader:
print(row)
open('[Link]', mode='w') opens the file
in write mode (w), and newline='' prevents
extra blank [Link]() creates a writer
object for writing to the [Link]() writes
a single row, while writerows() writes
multiple [Link]() reads each row as
a list.

You might also like