ch3 Notes Word

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

CS- File Handling 

A file is a document or the data stored in a permanent storage


device (data inside the file is termed as persistent data) which can
be read, written or rewritten according to requirement. In other
words, data is packaged up on the storage device as data
structures called files. All files are assigned a name that is used for
identification purposes by the operating system and the user.

Disk file 
1. The generated output is stored in these files, if I am storing
something in my file it is called disk writing. When we retrieve
the data from the file we read it. 
2. Data is stored in the form of bytes in the disk.
3. We can read data off disk files in the python program or write
back data from the python program to disk files. 
Standard input device- mouse, keyboard 
Standard output device- monitor
4. Data will be permanently stored in the disk files
5. .txt extension is used for text files

Types of files:

Text file- Is in human-readable form like notepad file. Har cheez is


readable in the form of a character and can be created using any text
editor. Dono Tarah key characters ko Kar sakte h txt file m (human-
readable and non-human readable). A line is a sequence of
characters (ASCII or UNICODE), stored on permanent storage
media. In a text file, each line is terminated by a special character,
known as END OF LINE(EOL). By default, the EOL character is the
new line character(\n).

Binary files- Binary files are used to store binary data such as
images, video files, audio files, etc. A binary file contains arbitrary
binary data, usually numbers stored in the file which can be used for
numerical operations. In a binary file, there is no delimiter for a
line. Also, no character translation can be carried out in a binary
file. As a result, binary files are much easier and faster than text files
for carrying out reading and writing operations on the data. Binary
files require specific programs to access their content.
Ski code and Unicode characters 
Unicode is the Information Technology standard that is used for
encoding, representation, and handling of texts in the writing
systems  

ASCII (American Standard Code for Information Interchange)


represents text in computers such as symbols, digits, uppercase
letters, and lowercase letters.
ASCII encodes only several letters, numbers, and symbols whereas
Unicode encodes a large number of characters.
Unicode is the IT standard that represents letters of English, Arabic,
Greek (and many more languages), mathematical symbols,
historical scripts, etc whereas ASCII is limited to few characters
such as uppercase and lowercase letters, symbols, and digits(0-9).

Use of os modules for creating directories (refer code)


1. To know in which directory you are working in currently- 
os.getcwd()  (current working directory)
1. For getting another directory in the present directory-  
os.chdir(“d://xii chapters”)
1. To make a directory- os.mkdir(“12cs’’)

How do we create a text file:


Open, read/write, close

● Difference between writing and append- append adds at the


last of the current detail and write is used to edit the current
detail in any way
● when you open a file in read mode, the given file must exist in
the folder, otherwise python will raise a filenotfounderror.

Opening a file : (refer code)


When we open a file, we are asking the operating system to find the
file by name and make sure the file exists.
Syntax to open a file:  file_object= open(filename,mode)   
(will create a reference link which is also known as file handler jo
user and file k beech m link establish krta h )

Different modes of opening a file: 


A file mode defines how the file will be accessed
(this is an optional parameter as the default mode is the read mode)
★ The file_object establishes a link between the program and the
data file stored in the permanent storage, and access modes
define the location of the file pointer, i.e, from where the data
has to be read and written to the file
★ when we work with files a buffer (area in memory where data
is temporarily stored before being written to the file)is
automatically associated with the file when we open it. while
writing the content to a file, it goes to buffer and once the
buffer is full data is written to the file. Also, when the file is
closed, any unsaved data is transferred to the file.
★ flush()- this function of file object is used to force
transfer of data from buffer to file
★ to open a file in binary mode, it should be suffixed
with ‘b’ to represent binary files.
Other ways of opening a file 
1. Using open function
2. Using try, exception and final 
3. Using with open (benefit of using with open is that we don’t
need to close the function) with open (mode) as (name of
file \handler)

Flush func()
Jab tak myfile.close() use nhi hoga tab tak text temporary buffer k
andr store hota h. 
If we simultaneously want to write our text in the notepad file
without closing our function then we use flush ()
Binary Description Notes
Text File File
Mode Mode

‘r’ ‘rb’ Read only File must exists, otherwise


Python raises
I/O errors
‘w’ ‘wb’ Write only If file not exists, file is created
If file exists, python will
truncate existing data and
overwrite the file.
‘a’ ‘ab’ Append File is in write mode only, new
data will be added to the end of
existing data i.e. no
overwriting. If file not exists it
is created
‘r+’ ‘r+b’ or ‘rb+’ Read and File must exists otherwise error
write is raised Both reading and
writing can take place
w+ ‘w+b’ or Write and read File is created if not exists, if
‘wb+’ exists data will be truncated,
both read and write allowed

‘a+’ ‘a+b’ or ‘ab+’ Write and read Same as above but previous
content will be retained and
both read and write.

Reading of a file: (refer questions of program in the code)


File can be read in three ways
1. Character by character 
2. Word by word
3. Line by line
★ How do we read word by word?
While true se bhi kr skte h usme special condition dalni padegi or
break statement bhi use krni padegi program m 
★ How do you read line by line? 
Readlines function is used 

There are ways of reading in a directory(refer code)


1. Read- if no. of bytes not provided it reads and returns in the
form of a string, to read the entire data from the file, starts
reading from the cursor up to the end of the file
2. read(n)- to read ‘n’ characters from the file, starting from the
cursor; if the file holds fewer than ‘n’ characters, it will read
until the end of the file
3. Readline- reads only till the specified bytes are in the
parameter but if no value is provided then it will read the
whole file, to read only one line from the file; starts reading
from the cursor up to, and including, the end of line character  
4. Readlines- returns the value of the whole file in the form of a
list. to read all lines from the file into a list; starts reading from
the cursor up to the end of the file and returns a list of lines,
separated by new line character’\n’
5. readable- it returns true if the file is readable
★ Readlines m split use nhi ho skta because usme multiple lines
hoti h but readline m esa ho skta h becoz usme Ek hi line hoti
h

Closing of a file:
1. fileobject.close()
2. a close() function breaks the link of file object and the file on
the disk
3. after closing a file(using close()), no tasks can be performed on
that file through the file-object

9th August 2021


How to update or delete a particular record 
Dusri file m data write krate jayenge agar esa krna h to 

11th august 2021


seek()
In Python, seek() function is used to change the position
of the File Handle to a given specific position. File handle
is like a cursor, which defines from where the data has to
be read or written in the file.

12th August 2021

File pointer- helps us move the cursor on the file wherever we


want.for moving we use seek(), for moving on a particular
position we use tell()
Refer ppt for reference points and all parameter wala 

1 and 2 do not wwork on text files 


13th aug 2021
Binary files:
Extension of binary file is .dat (data files)
Logical name is used as extension 
Binary file m data binary format m store hota h
(computer readable format zeros and ones)
When we try to open it in notepad then the data is
portrayed in the computer readable form.
Faster than text files because it does not needs to get
converted into human readable language.
We can store large data files like video, images,
dictionaries using binary files .
All the methods(another name of functions) will remain
same like text files only 2 new modules will be
introduced which are available in the pickle module 
Pickling- when we write the data in the file, we are
converting objects(lists, etc) to a stream of bytes.
(marshelling, slashening) 
Unpickling- when data is written in bytes then converting
it back to the object then it is called unpickling 
Pickling is the act of converting objects to a stream of
bytes. You can use in-built module pickle to flatten
complex object hierarchies into a byte stream.
Unpickling is the inverse operation, whereby a byte
stream is converted back into an object hierarchy.
Pickling is alternatively known as "serialization",
"marshalling", or "flattening".
1. Dump() 
2. Load()

16th august 2021


Bytearray- has the limitiation of writing the data from 0-
256 in a list, iske baad agar hum 259 lete h to it will
show an error.

import pickle
#create a dictionary
phonebook = {
'Deepak':98107593,
'Saksham':92104584,
'John':87989898
}

#open file in binary mode for writing.


outfile = open('phonebook.dat', 'wb')

#serialize the object and writing to file


pickle.dump(phonebook, outfile)

#close the file


outfile.close()

import pickle

#open file in binary mode for reading


infile = open('phonebook.dat', 'rb')

#reading the oject from file


phonebook = pickle.load(infile)

#display the phonebook


print(phonebook)

#close the file


infile.close()

21st august 2021(recording also)


did random files in the previous class, using tell function

update() =explanation
rb+ stands for reading and writing in binary file
tell ()-

26th aug
[0:18 pm, 26/08/2021] Aman: import pickle
l=[]
def add():
while True:
f=open("Bus.dat","wb")
a=int(input("Enter Bus Number...?"))
b=input('Enter Starting Point')
c=input("Enter Destination")
dat=[a,b,c]
l.append(dat)
n=input("Do you want to enter more..?")
if n=="n":
break
f.close()

pickle.dump(l,f)

def search():
with open("Bus.dat","rb") as f:
s=pickle.load(f)
for i in s:
if i[2]=="cochin":
print(i)
add()
search()
[0:19 pm, 26/08/2021] Aman: import pickle
def add():
while True:
ls=[]
with open("product.dat" ,"wb+") as f:
a=int(input('Enter prodcut code...'))
b=input("Enter product price..")
l=[a,b]
ls.append(l)
print()
print()
n=input("Enter more?")
if n=="n":
pickle.dump(ls,f)
break
add()
pc=int(input("Enter product code to be searched.."))
def searchprod(pc):
with open("product.dat","rb") as f:
s=pickle.load(f)
for i in s:
if i[0]==pc:
print("Product Found!!")
print()
print()
print(i)
else:
print("No product found")
searchprod(pc)
[0:19 pm, 26/08/2021] Aman: import pickle
def add():
while True:
ls=[]
with open("route.dat" ,"wb+") as f:
a=int(input('Enter route number...'))
b=input("Enter route destination..")
c=input("Enter route name")
l=[a,b,c]
ls.append(l)
print()
print()
n=input("Enter more?")
if n=="n":
pickle.dump(ls,f)
break
add()
rc=int(input("Enter route number to be modified.."))
def routechange(rc):
with open("route.dat","wb+") as f:
s=pickle.load(f)
for i in s:
if i[0]==rc:
i[0]=j
print("Route Found!!")
print(i)
print(s[j])
routechange(rc)
[0:20 pm, 26/08/2021] Aman: import pickle
def add():
while True:
ls=[]
with open("class.dat" ,"ab+") as f:
a=int(input('Enter roll number...'))
b=input("Enter name..")
c=input("Enter percentage")
l=[a,b,c]
ls.append(l)
print()
print()
n=input("Enter more?")
if n=="n":
pickle.dump(ls,f)
break
add()
def remcount():
count=0
with open('class.dat',"rb") as f:
s=pickle.load(f)
print(s)
for i in s:
if int(i[2])<40:
count+=1
print(count,"students need remedials")

remcount()

1. Write a function in python to search and display details, whose destination is “Cochin” from
binary file “Bus.Dat”. Assuming the binary file is containing the following elements in the list:
2. 1. Bus Number
3. 2. Bus Starting Point
3. Bus Destina

Write a function addrec() in Python to add more new records at the bottom of a binary file
“STUDENT.dat”, assuming the binary file is containing the following structure :
[Roll Number, Student Name]

Write a function searchprod( pc) in python to display the record of a particular product from a
file product.dat whose code is passed as an argument. Structure of product contains the
following elements [product code , product price]

Write a function routechange(route number) which takes the Route number as parameter and
modify the route name(Accept it from the user) of passed route number in a binary file
“route.dat”. Which contains routeno destination route name as records

Amit is a monitor of class XII-A and he stored the record of all the students of his class in a
file named “class.dat”. Structure of record is [roll number, name, percentage]. His computer
teacher has assigned the following duty to Amit
Write a function remcount( ) to count the number of students who need remedial class
(student who scored less than 40 percent)
4. View assignment

5. Material

You might also like