0% found this document useful (0 votes)
25 views

File Handling New

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)
25 views

File Handling New

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
You are on page 1/ 64

WHY THERE IS A NEED OF FILE

HANDLING?
A file in itself is a bunch of bytes stored on some
storage device.
File helps us to store the data permanently, which
can be retrieved for future use
TYPES OF FILES
TEXT FILES
BINARY FILES
CSV (COMMA SEPARATED VALUES) FILES
TEXT FILES
Stores information in ASCII or Unicode characters
Each line of text is terminated with a special character
known as EOL(End Of Line)
Extension for text files is .txt
Default mode of file
BINARY FILE
Contains information in the same format in which the
information is held in memory
There is no delimiter for a line
No translations are required
More secure
Difference between text files and Binary
files
Text file Binary file

Text files stores information in ASCII Binary files are used to store binary
characters data such as images, audio , video and
text
Each line of text is terminated with a There is no delimiter in Binary file
special character known as EOL (End
Of Line)
Text files are easy to understand Binary files are difficult to understand
because these files are in human
readable form
Text files are slower than binary files Binary files are faster and easier for
program to read and write as compared
to text files
Text files are having the extension .txt Binary files are having the
extension .dat
OPENING A FILE
TWO METHODS TO OPEN A
FILE

USING OPEN() FUNCTION


USING WITH STATEMENT
HOW TO OPEN A TEXT FILE
FileObject=open(<filename>)

OR

FileObject=open(<filename>,<mode>)
Example
F=open(“myfile.txt”,r)
F=open(“C:\\Users\\sony\\Desktop\\myfile.txt”,”r”)
F=open(r“C:\Users\sony\Desktop\myfile.txt”,”r”)
USING WITH STATEMENT
This method is very handy when you have two related
operations which you would like to execute as a pair, with a
block of code in between.

Syntax:
with open(<filename>,<filemode>) as <fileHandle>:
f.write(“……”)
Benefits of using with statement
It automatically closes the file after the nested block of
code.
It also handles all the exceptions occurred before the
end of block.
Example
with open(“Output.txt”,”w”):
f.write(“Text”)
DESCRIPTION

Open
FILE file for
ACCESS reading
MODES only. This is the default mode.

Opens file for reading in binary format. This is the default mode

Opens a file for both reading and writing

Opens a file for both reading and writing in Binary format

Opens a file for writing only. Overwrites the file if already exists,else creates a new file

Opens a file for writing only in binary format.


Opens a file for both reading and writing

Opens a file for both reading and writing in binary format

Opens a file for appending. The file pointer is at the end of the file if the file exists. If th
it creates a new file for writing.

Opens a file for appending in binary format.

Opens a file for both appending and reading


r+ mode w+ mode

Used for both reading and writing w+ mode is also used for both reading
and writing

In r+ mode, the file pointer is at the In w+ mode, the file pointer is at the
beginning of the file. end of the file

If the file doesnot exists, it will display If the file doesnot exist, it will create
the FileNotFoundError the new file

If the file exist, it doesnot show any If the file exists, it will write the data in
error the file (overwriting the previous
content)
READING DATA FROM A FILE
read()
readline()
readlines()
read()
Reads at most n bytes; if no n is specified, reads the
entire file.
Returns the read bytes in the form of a string
Syntax:
<Filehandle>.read([n])
readline()
Reads a line of input. If n is specified reads at most n
bytes.
Returns the read bytes in the form of a string ending
with ‘\n’ character.
Returns a empty string if no more bytes are left for
reading in the file
Syntax: <Filehandle>.readline()
readlines()
Reads all the lines of a text file
Returns in the form of list
Syntax:
<Filehandle>.readlines()
WRITE A METHOD IN PYTHON TO READ THE
CONTENT FROM A TEXT FILE “POEM.TXT”
LINE BY LINE AND DISPLAY THE SAME ON
THE SCREEN
WRITE A METHOD IN PYTHON TO READ THE
CONTENT FROM A TEXT FILE “POEM.TXT”
LINE BY LINE AND DISPLAY THOSE LINES
WHICH ARE STARTING WITH THE ALPHABET
“h”
WRITE A METHOD IN PYTHON TO COUNT THE
NUMBER OF LINES FROM A TEXT FILE
“POEM.TXT” WHICH ARE STARTING WITH AN
ALPHABET “h”
WRITE A METHOD IN PYTHON TO READ LINES
FROM A TEXT FILE “POEM.TXT” AND DISPLAY
THOSE LINES WHICH ARE EITHER STARTING
WITH AN ALPHABET “h” OR STARTING WITH
AN ALPHABET “t”
WRITE A METHOD IN PYTHON BIGLINES() TO
READ LINES FROM A TEXT FILE “POEM.TXT”
AND DISPLAY THOSE LINES WHICH ARE
BIGGER THAN 30 CHARACTERS
HOW TO WRITE DATA IN A FILE
write()
writelines()
WHILE WRITING DATA IN A
FILE
If file doesn’t exists, it will create the new file
If file exists, it will overwrite the data in the file
write(string)
write() method takes a string and writes it in the file.
For storing data, with EOL character, we have to add
“\n” character to the end of the string
For storing numeric value, we have to either convert it
into string using str() or write in quotes.
writelines()
writelines() method is used to write sequence data
types in a file (string,list and tuple)
CLOSING FILES
A close() function breaks the link of file-object and the
file on the disk.
After close(), no tasks can be performed on that file
through file object on file handle.

Syntax:
<FileHandle>.close()
APPENDING DATA TO A FILE
Append means to add the data at the end of file using
‘a’ mode.
If file doesn’t exists, it will create the new file
If file exists, it will append the data at the end of the
file.
WAP TO READ DATA FROM A
TEXT FILE “POEM.TXT” AND
REMOVE THE MULTIPLE
SPACES WITH A SINGLE
SPACE . WRITE THE DATA IN A
FILE “NEW.TXT”.
WAP TO READ DATA FROM
A TEXT FILE AND PRINT
ONLY THE NUMBERS OR
DIGITS FROM THE FILE
AND ALSO COUNT THE
TOTAL NO. OF DIGITS
WAP TO READ DATA FROM THE TEXT FILE
“POEM.TXT” AND DISPLAY THOSE WORDS,
WHICH ARE ENDING WITH “E”.
WAP TO READ DATA FROM A TEXT FILE
“POEM.TXT” AND CALCULATE AND DISPLAY
THE SUM OF ALL THE EVEN DIGITS PRESENT IN
A TEXT.
RANDOM ACCESS METHODS
seek()
tell()
seek()
seek() function is used to change the position of the
file handle (file pointer) to a given specific position.
File pointer is like a cursor, which defines from where
the data has to be read or written in the file.
Syntax:
f.seek(offset,from_what)

#where f is the file pointer


seek()
The reference point is defined by the “from_what”
argument. It can have any of the three values:
0: sets the reference point at the beginning of the file,
which is by default.
1: sets the reference point at the current file position.
2: sets the reference point at the end of the file

But in Python 3.x and above, we can seek from


beginning only, if opened in text mode. We can
overcome it by opening the file in b mode
tell()
It returns current position of the file pointer object.
It doesnot take any parameters and returns an integer
value. Initially file points to the beginning of the file
(if not opened in append mode). So the initial values of
tell() is zero.
BINARY FILES
Most of the files that we see in our computer system
are called binary files.
Image files: .jpg,.png,.gif,.bmp,etc.
Video files: .mp4,.3gp,.mkv,.avi,etc.
Audio files: .mp3,.wav,.mka,.aac, etc.
Archieve files: .zip,.rar,.iso,.7z etc.
Executable files: .exe,.dll,.class etc.
Pickling
Pickling refers to the process of converting the
structure (such as list or dictionary)) to a byte stream
before writing to the file.
Unpickling
Unpickling refers to the process of converting the byte
stream back to the original structure.
pickle.dump()
Used to write the object in a file
Syntax:
pickle.dump(<Structure>,FileObject)

Where
Structure can be any sequence of Python. It can be
either list of dictionary.
File Object is the file handle of the file, in which we
want to write.
pickle.load()
Used to read the data from a file
Syntax:
Structure=pickle.load(FileObject)

Where
Structure can be any sequence of Python. It can be
either list of dictionary.
File Object is the file handle of the file, in which we
want to write.
CSV FILES
CSV stands for Comma Separated Values
CSV is just like a text file, in human readable format
which is extensively used to store tabular data in a
spreadsheet database
The separator character of CSV files is called a
delimiter. Default delimiter is comma(,). Other
delimiters are tab(“\t”),colon(:),pipe(|),semi colon(;)
characters.
CSV FILES
Each record consists of fields separated by
commas(delimiter)
ADVANTAGES OF CSV FILES
Easier to create
Preferred import and export format for databases and
spreadsheets
Capable of storing large amount of data
Python csv module
csv module provides two types of objects:
reader- to read from the csv files
writer- to write into the csv files
 To import csv module in our program, write the
following statement:
import csv
Opening/Closing csv files
Open a csv file
f=open(“stu.csv”,”w”)
OR
f=open(“stu.csv”,”r”)

Close a csv file


f.close()
Role of argument newline in opening a csv
file
Newline argument specifies how would Python handle
new line characters while working with csv files, on
different operating systems
Different operating systems store EOL characters
differently
EOL characters used in different operating
systems
SYMBOL/CHAR MEANING OPERATING SYSTEM

CR[\r] Carriage Return Macintosh

LF(\n) Line Feed UNIX

CR/LF[\r\n] Carriage Return MS DOS, WINDOWS

NULL[\0] Null character Other OS systems


Note:
Additional optional argument as newline=‘’ (null
string no space in between) with file open() will ensure
that no translation of End of Line(EOL) character
takes place.
WRITING IN csv FILES
csv.writer() Returns a writer object which writes
data into csv files

<writerObject>.writerow() Writes one row of data on to the writer


object.

<writerObject>.writerows() Writes multiple rows on to the writer


object.
Role of writer object
The csv.writer() function returns a writer object that
converts the user’s data into a delimited string.
This string can later be used to write into CSV files
using the writerow() function or writerows() function.
import csv
f=open("Student.csv","w")
s_writer=csv.writer(f)
s_writer.writerow(["roll","name","marks"])
rec=[]
while True:
r=int(input("Enter roll"))
n=input("Enter name")
m=int(input("Enter marks"))
lst=[r,n,m]
rec.append(lst)
ch=input("Do you want to enter more records(y/n)")
if ch=='n':
break
for i in rec:
s_writer.writerow(i)
import csv
f=open("Student.csv","w“,newline=‘’)
s_writer=csv.writer(f)
s_writer.writerow(["roll","name","marks"])
rec=[]
while True:
r=int(input("Enter roll"))
n=input("Enter name")
m=int(input("Enter marks"))
lst=[r,n,m]
rec.append(lst)
ch=input("Do you want to enter more records(y/n)")
if ch=='n':
break
for i in rec:
s_writer.writerow(i)
f.close()
import csv
f=open("Student.csv","w“,newline=‘’)
s_writer=csv.writer(f,delimiter=‘;’)
s_writer.writerow(["roll","name","marks"])
rec=[]
while True:
r=int(input("Enter roll"))
n=input("Enter name")
m=int(input("Enter marks"))
lst=[r,n,m]
rec.append(lst)
ch=input("Do you want to enter more records(y/n)")
if ch=='n':
break
for i in rec:
s_writer.writerow(i)
f.close()
import csv
f=open("Student.csv","w“,newline=‘’)
s_writer=csv.writer(f,delimiter=‘;’)
s_writer.writerow(["roll","name","marks"])
rec=[]
while True:
r=int(input("Enter roll"))
n=input("Enter name")
m=int(input("Enter marks"))
lst=[r,n,m]
rec.append(lst)
ch=input("Do you want to enter more records(y/n)")
if ch=='n':
break
for i in rec:
s_writer.writerows(rec)
f.close()
Reading from csv files
To read data from a CSV file, reader function of csv
module is used.

csv.reader()
Returns a reader object. It loads the data from CSV file
into an iterable after parsing delimited data.
def read():
f=open("Student.csv","r“)
s_reader=csv.reader(f)
for i in s_reader:
print(i)
f.close()
def read():
f=open("Student.csv","r“,newline=“\r\n”)
s_reader=csv.reader(f)
for i in s_reader:
print(i)
f.close()

You might also like