Topic: Data File Handling
1.Path :
a.Absolute path - path to be given if the working
directory is different from the file location.
Eg: “d:/pythonfile/sample.txt”
b.Relative path- Path to be given if the file is in the
working directory.
Eg: “sample.txt”
2.Mode of file:
a.read mode - “r “
b.write mode - “w”
c.append mode - “a”
Computer Science
Topic: Data File Handling
Computer Science
Topic: Data File Handling
3. Steps for File Handling:
a. Opening a file :
i. Function used open() ,
Computer Science
Topic: Data File Handling
OR
with open(filename, mode) as fileobject :
Examples:
OR
Question:
1. Write a python statement to open “Peom.txt” file in read mode using both
methods.
2. Write a python statement to open “Sample.txt” file in write mode using both
methods
3. Write a python statement to open “Peom.txt” file in append mode using both
methods.
Computer Science
Topic: Data File Handling
b. Operations
i. Function used.
Reading - read(), readline(), readlines()
SYNTAX:
a. Variable = fileobject . read()
b. Variable = fileobject . read(n) # n is the number of bytes.
c. Variable = fileobject . readline()
d. Variable = fileobject . readlines()
Practical Questions :
1. Write a program to read a file and display the content from the
file “Sample.txt”.
2. Write a program to read a file “Sample.txt” and display the
number of words present in the file.
3. Write a program to read a file sample.txt and display the number
of lines.
4. Write a program to count the word “my” in the file “Sample.txt”.
Computer Science
Topic: Data File Handling
Writing in a text file:
Computer Science
Topic: Data File Handling
Computer Science
Topic: Data File Handling
Computer Science
Topic: Data File Handling
Computer Science
Topic: Data File Handling
Question for Assignment
Write a program to read from “first.txt” file and write the
content in “second.txt” file.
c. Closing a file
i. Function used close()
SYNTAX :
fileobject.close()
Computer Science
Topic: Data File Handling
Practical Test:
Write a menu driven program to read and write the data in the
Student.txt file.
1. writing(): To accept and store atleast 5 records of students
which includes, roll_no, name and marks.
2. Reading(): To read data from Student.txt file and display on
screen.
FILE Pointer functions : tell() and seek() - Random Access in file.
tell(): To retrieve the current position
Syntax:
fileobject.tell()
f.tell()
seek(): To move the file pointer. It take two parameter
Offset : number of bytes to move
From_what : (0,1,2) - it can have either of these values
0 - Default value - from the beginning of the file.
1 - From the current position of the file.
2- From the end of the file.
Computer Science
Topic: Data File Handling
*************************************************************************************
Binary Files Operations
Binary File: Basic operations on a binary file: Open (filename – absolute or
relative path, mode) / Close a binary file,
Pickle Module – methods load and dump; Read, Write/Create, Search, Append
and Update operations in a binary file.
1.Path :
a.Absolute path - path to be given if the working
directory is different from the file location.
Eg: “d:/pythonfile/sample.dat”
b.Relative path- Path to be given if file is in working
directory.
Computer Science
Topic: Data File Handling
Eg: “sample.dat”
Mode of binary files:
c.read mode - “rb “
d.write mode - “wb”
e.append mode - “ab”
Module used : pickle
Eg: import modulename ---- import pickle
from modulename import method1,method2
from pickle import load,dump
Method used : load() and dump()
load (fileobject) : read data from binary file.(unpickling)
dump(data , fileobject): write data to binary file. (pickling)
Operations in binary file:
1.Writing - using dump(what,where)
Computer Science
Topic: Data File Handling
Code :
Create a binary file “UAE.dat” which stores the information such as
Emirates_Id, Name, and Visa Number.
R={“ID”:eid,”Name”: name,”VN”:visa}
The code executed twice and below given are the input for the binary file.
Computer Science
Topic: Data File Handling
Question:
Create function ADD_Record() to store information about books in the book.dat
file. Information are as follows : book id, book name, book price, quantity.
Create a binary file “Student.dat” which stores the information such as
rollno,name and percentage.
Reading
Computer Science
Topic: Data File Handling
`
f=open(“sample.dat”,”rb”)
Search operation :
Computer Science
Topic: Data File Handling
Computer Science
Topic: Data File Handling
Home Work :
Write a function based program and create the below
functions, Display a menu for calling those functions.
1.Add a book record in the book.dat file.
[b_id,b_name,quantity,price] - ADD()
2.Display all the records added to “book.dat”- SHOW()
3.Display all the records of books whose quantity is more
than 10. - SEARCH()
4.Update the quantity of the book by taking book id as
input.
Binary Update
def update(id, nname):
flag = False
records = []
try:
with open("Teacher.dat", "rb") as f:
while True:
rec= pickle.load(f)
if rec[0] == id:
rec[1] = nname # Update the name field
flag = True
records.append(rec)
Computer Science
Topic: Data File Handling
except:
pass
with open("Teacher.dat", "wb") as f:
for i in records:
pickle.dump(i, f)
if flag :
print("Record updated")
else:
print("Teacher id not found")
Write an interactive menu driven program to perform the
following operations on a data file
“Teacher.dat” which stores the information such as
Teacher_Id, Teacher_Name, and Designation.
1. CREATE (To createTeacher.dat with some records)
2. SEARCH( to search a record using Teacher_ID)
3. DISPLAY (To display all records of Teacher.dat file)
4. UPDATE(Update the teacher name by taking ID as
input)
Update Operations :
1. Import module - os and pickle
2. Open file, in which file needs to be updated in read mode.
3. Open a new file in write mode.
Computer Science
Topic: Data File Handling
4. Copy each record from the existing old file to the new file one by one.
5. Compare each record after reading if it matches the condition to update
then add new value and paste in the new file, else repeat the step 4 until all
records are transferred.
6. Delete old file (open in step2)
7. Rename new file with old file name(opened in step 3).
Computer Science
Topic: Data File Handling
File Existing Data :
Another Method to update file :
Objectives – Students will be able to,
● Recollect the operations, modules, and functions utilized when working with
binary files.
● Associate the CSV module operation with binary file functions.
● Apply the csv file function to create a hospital.csv file that stores huge records
of all hospitals available across the UAE as a single point of access..
Computer Science
Topic: Data File Handling
CSV File and Operations with it
● A CSV is a comma-separated values file, which allows data to be saved in a
tabular format.
● CSVs look like a garden-variety spreadsheet but with a . csv extension.
● CSV files can be used with most any spreadsheet program, such as Microsoft
Excel or Google Spreadsheets.
● CSV files are often used to transfer data between different types of software,
applications, and databases.
> Module name - csv
> Importing statements
● import csv
● import csv as c
● from csv import *
> Modes of file will be the same as textfile.
r, w, a, etc…..
Writing function
● First create a writer object using writer(fileobject) of
csv module.
● Writerow (data) writes data to file.
○ Syntax : writerobject.writerow()
Computer Science
Topic: Data File Handling
Reading function: csv.reader(fileobject )
Questions Level based completion
Creating File Reading from File Searching from
file
Computer Science
Topic: Data File Handling
Write a function based Display () to display all Write a function based
program to create a CSV the record available in program to create a CSV
file to to create hospital.dat file file to to create
Hospital.CSV file to store Hospital.CSV file to store
information about all the information about all the
hospitals across UAE. hospitals across UAE.
(Add at least 10 records 1. Functions to add
for the same) record to file
2. Function to display
Record such as, records from the
[Hospitalid, Hospital file.
name, location, 3. Function to search
License_No ] for records from
the file by taking
Hopital License ID
and displaying its
details.
Research :
How do Python libraries for CSV file operations handle data serialization and
deserialization, and what are the implications for interoperability with other data formats
and systems?
Computer Science
Topic: Data File Handling
Computer Science
Topic: Data File Handling
Computer Science
Topic: Data File Handling
Computer Science
Topic: Data File Handling
Computer Science
Topic: Data File Handling
Computer Science
Topic: Data File Handling
CSV Files
1.Comma Separated Value
2.Extensions is, .csv
3.Used to handle large amount of data
4.These stores data in the form of plain text file like ASCII ,
Unicode form.
5.Data stored in tabular form, separated by comma.
6.Why are CSV files used?
7.How they are different from Text.
Computer Science
Topic: Data File Handling
Computer Science