Nothing Special   »   [go: up one dir, main page]

File Handling 1

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 72

FILE HANDLING -NEED

• When a program is executed, the output will


be visible on the screen as per the input the
programmer is providing but the moment you
shift to program, or after computer shut down
the output that you could see on the screen
cannot be retrieved once again as the data
which was visible on the screen was not saved
as a file in any permanent location.
FILE HANDLING-KINDS OF FILES

The data files store data pertaining to some


applications. There are two kinds of files
1.Text files 2. Binary files
The extension of text file is .txt
The extension of binary file –variety of
extensions(any application defined extensions. For
eg. dat)
FILE HANDLING-KINDS OF FILES

Text files stores information in the ASCII format

Each line of text is terminated with special EOL


character which is different for different OS.

In python, the default EOL characters are ‘\n’, ‘\r’,


‘\r\n’
FILE HANDLING-BASIC OPEATIONS
EOL characters are operating system dependant . It
varies from one Os to other operating system.
SYMBOL/CHAR OPERATING SYSTEM

\r MACINTOSH

\n UNIX

\r\n MS-DOS,WINDOWS,OS/2

\0 OTHER OSs
FILE HANDLING-KINDS OF FILES
The text can be a
1.Regular text file-stores the content in the file in
whatever it was accepted for writing.
2.Delimited Text files:-it takes a specific character
to separate the values.
1.Tab Separated Value Files:-takes tab to
separate values. (extension is .txt, .csv)
2. Comma Separated Value Files:-takes comma
to separate values(extension is .csv)
FILE HANDLING-DIFFERENCES
Text file Binary file

Text files store information in the ASCII Binary files store data in the format in
Format which ever way it is stored in memory

Text files each line is terminated with No EOL CHARACTER


special EOL character

Special translations take place when it No such translations take place as there is
encounters special EOL character no EOL

To fetch content from file it takes more Writing to file and reading from files are
time .query processing is slower because faster. Query processing is faster because
data is stored in ASCII FORMAT the data is stored in machine readable
format.

The extension of the text file is .txt The extension of the binary file is .dat
FILE HANDLING-BASIC OPEATIONS
The basic file manipulations are
reading
writing
appending contents to file.
open() function is used to open the file.
close() function is used to close the file.
FILE HANDLING-FILE PATH

The format for opening and closing files


f=open(“c:\\temp\\file\\series.txt”,”w”) if the
programmer wants to create the file in temp
folder of c drive.
If the programmer wants to create the file in the
same folder of the same drive where you python
is available, then the programmer does not
require to specify the path.
f=open(“series.txt”, ”w”)
FILE HANDLING-FILE PATH
• f=open(“c:\\temp\\file\\series.txt”,”w”)
• Here in the above way of opening the file, we
need to put double slash as \t in temp stands for
tab. In order to communicate that he does not
mean \t for tab , the programmer has to put
double slash
• If the programmer does not want to put double
slash then the entire path should be preceded
with r to inform that it is raw data no special
meaning is attached to \t in the following manner
• f=open(r"c:\temp\content.txt")
FILE HANDLING

f is known as file object or file handle


which is a reference to the file which
is created in the memory.
Second parameter is to show the
mode of the file which means the file
is opened in read/write/append
mode
FILE HANDLING-TEXT FILES

f=open(“series.txt”)
In the above statement the file series.txt is opened in
read mode.
By default the file is opened in the read mode if mode
of the file is not mentioned.
In order to read the file first of the file needs to be
created and content should be written to the file.
FILE HANDLING
Close() –it is used to the close the file.

f.close() where f is the file object/file handle

It is a good programming habit to close the file once the


work is completed.

If the file is not closed , sometimes accidental changes may


happen to the file. the programmer may sometimes fail to
do the required operation.
FILE HANDLING
by default the file pointer is always at the beginning of
the file.

If the file with some content is existing , if the


programmer executes the same program to write
contents to file which is in write mode, then the
previous all contents are over written. The file is created
with new content as file is not in append mode()
FILE HANDLING-FILENOTFOUNDERROR
when the file opened in the write mode, if the
file is existing already then the contents of the
file are truncated as the file pointer is in the
beginning of the file and the new content will be
written to the file .
If the file is not existing and the user opens the
file in the read mode then “FileNotFoundError”
error will be shown.
FILE HANDLING-WRITING TO FILE
For writing contents to files we have 2 functions

write (st) for writing the string to the file. Write


function takes string as a parameter.

writelines(list) takes list as a parameter and writes


the content of the list to the file.
 
FILE HANDLING-WRITE()
n=int(input("how many strings you want to
accept"))
f=open("series1.txt",'a')
for i in range(n):
st=input("accept the string")
f.write(st)
f.write('\n')
f.close()
print("file created successfully")
FILE HANDLING-WRITE()

INPUT TO THE FILE:-


this is good
this is ok
all are fie
slow and steady wins the race
all is well
better late than never

The above content was accepted as string so the same has


gone to the file. The value accepted in the string is 6.
FILE HANDLING-WRITELINES()
f=open("series.txt","w")
n=int(input("enter the size"))
l=[["True"]for i in range(n)]
for i in range(n):
l[i]=input("enter")
f.writelines(l)
f.close()
FILE HANDLING
INPUT TO THE FILE:-

NO PAIN NO GAINsuccess is not an overnight


achievementadversity is source of learning
FILE HANDLING-READ()
read(n)—read functions reads ‘n ‘ number of
bytes from the file that is opened for reading

read()-read function without any parameter


reads the entire file.
FILE HANDLING-READ(N)
f=open("series1.txt","r")
n=int(input("how many bytes you want to
read"))
data=f.read(n)
print(data)
f.close()
FILE HANDLING-READ(N)
If input is 5
The output will be
This (space is also included after
This)
Note:-after this space is also counted
as 1 bit of information.
FILE HANDLING-READ()

f=open("series1.txt","r")
data=f.read()
print(data)
f.close()
FILE HANDLING-READ()
Output:-
this is good
this is ok
all are fine
slow and steady wins the race
all is well
better late than never

The entire content of the file was read as number of


bytes were not passed as a parameter.
FILE HANDLING-READLINE()
readline()-reads only one line from the file. It
reads the line till it encounters the next line
character. If next line not encountered on account
of not inserting at the time of writing the file, then
the whole content of the file will be fetched.

If the file contains n number of lines then


readline() will read only 1 line at a time from the
position of file pointer.
FILE HANDLING-READLINE(N)

readline(n)—if readline() function


takes no of bytes as a parameter then
it reads only ‘n’ number of bytes. It
works like read(n) function.
FILE HANDLING-READLINE(N)
f=open("series1.txt","r")
data=f.readline()
print(data)
data=f.readline()
print(data)
data=f.readline(3)
print(data)
data=f.readline(5)
print(data)
f.close()
FILE HANDLING-READLINE(N)
CONTENT OF SERIES1.TXT
this is good
this is ok
all are fine
slow and steady wins the race
all is well
better late than never

OUTPUT:

this is good

this is ok

all
are (along with space both sides 5 characters)
FILE HANDLING-READLINES()
readlines()-This function reads all lines
from the file if more than one line of
data is in the file and returns data in the
form of a list. The list also contains next
line character.
f=open("series1.txt","r")
data=f.readlines()
print(data)
FILE HANDLING-READLINES()

OUTPUT:-

['this is good\n', 'this is ok\n', 'all are fine\


n', 'slow and steady wins the race\n', 'all is
well\n', 'better late than never\n']
FILE HANDLING-FILEPATH
f=open(r"c:\temp\series.txt").read(5)
One can open the file and read data by writing
the code in above manner . In the above
syntax file is opened in the read mode and 5
bytes were read.
f=open("c:\\temp\\series.txt").readline()
In the above examples f is not playing the role
of file object or file handle.
FILE HANDLING-FILE MODES
TEXT FILE DESCRIPTION OPERATIONS

‘r’ read mode Default mode . File should exist for reading .
Otherwise “FileNotFoundError” will be thrown
‘w’ Write mode Opens the file in write mode only. If file does not
exist it creates the file in write mode. If file
exists, the contents will be truncated as the
content will be overwritten. Whenever the
‘a’ Append mode Opens the file in append mode . The file pointer
goes to the end of the file if the file is already
created with content. If the file does not exist , it
will create a file
FILE HANDLING-FILE MODES
TEXT FILE DESCRIPTION OPERATIONS

‘r+’ Read and write Both reading and writing are possible but file
must exist otherwise it will throw
“FileNotFoundError” will be thrown.
‘w+’ Write and read Both reading and writing are possible.
If the file does not exist file will be created.
If the file exists already then contents will be
truncated.
‘a+’ Write and read Both reading and writing operations can be
performed.
If the file does not exist file will be created.
If the file exist then the file pointer will go the
end of the file and new content will be
appended.
FILE HANDLING

f.flush()-this function forces the data


to be written to file if at all not
written.
f.flush()
FILE HANDLING
seek()- function bring the file pointer to the
required location.
seek take either 1 parameter or 2
parameters.
1st parameter is called offset-where the
programmer mentions the number of bytes
2nd parameter specifies the position
FILE HANDLING
If the second parameter is 0 then the file pointer starts
moving the pointer from the beginning of the file by ‘n’
number of bytes specified as the first parameter.

If the second parameter is 1 then the file pointer starts


moving the pointer from the current position in the file
by ‘n’ number of bytes specified as the first parameter.

If the second parameter is 2 then the file pointer starts


moving the pointer from the end of the file by ‘n’
number of bytes specified as the first parameter.
FILE HANDLING
If the first parameter of the seek() function
is ‘+n’ number of the bytes then then
pointer will move in forward direction.

If the first parameter of seek() function is ‘–


n’ number of bytes then the pointer will
move in the backward direction.
FILE HANDLING
If the file pointer is at the beginning
of the file it is not possible to move in
the backward direction.

If the file pointer is at the end of the


file then it is not possible to move in
forward direction.
FILE HANDLING

Tell()-this function informs number of bytes


read in the file. It returns number of bytes
read so far.
C=f.tell()
C is storing the number of bytes read so far.
FILE HANDLING
f.seek(30)- as second parameter is not
mentioned the file pointer goes to 30th byte
from the beginning of the file
f.seek(4,1)—from the current position the file
pointer moves ahead by 4 bytes
f.seek(-4,1)- from the current position the file
pointer moves goes back by 4 bytes
FILE HANDLING
f.seek(4,2)—not possible. The file
pointer is already at the end of the file.

f.seek(-4,2)- from the end of the file the


file pointer moves back by 4 bytes

f.seek(-4,0)-not possible
FILE HANDLING-BINARY FILES
The binary files are stored with .dat extension or any application
defined extension.

The pickle package should be imported to the program for getting


an access to some functions like dump(), load()

The content of the binary is not readable as the data is not stored
in the form of ASCII

The content is stored in the form of machine readable format/byte


stream.
FILE HANDLING
The process of conversion of object hierarchy to byte
code( machine readable format) is known as “pickling”.
Pickling is also known as serialization.

The process of converting the byte code (which is in


machine readable format) to object hierarchy ( to human
readable format) is known as “unpickling”
FILE HANDLING

dump(object,fileobject) is used to dump the


object in to the file with the help of the file
object.-(pickling)

Load(f) is used to fetch the content from the


binary file.(unpickling)
FILE HANDLING-FILE MODES
BINARY DESCRIPTION OPERATIONS
FILE
‘rb’ read mode Default mode . File should exist for reading .
Otherwise “FileNotFoundError” will be thrown
‘wb’ Write mode Opens the file in write mode only. If file does not
exist it creates the file in write mode. If file
exists, the contents will be truncated as the
content will be overwritten.
‘ab’ Append mode Opens the file in append mode . The file pointer
goes to the end of the file if the file is already
created with content. If the file does not exist , it
will create a file
FILE HANDLING-FILE MODES
BINARY FILE DESCRIPTION OPERATIONS

‘rb+’/’r+b’ Read and write Both reading and writing are possible but file
must exist otherwise it will throw
“FileNotFoundError” will be thrown. The file
pointer is always at beginning of the file
‘wb+’/’w+b’ Write and read Both reading and writing are possible.
If the file does not exist file will be created.
If the file exists already then contents will be
truncated. The file pointer is always at the
beginning of the file.
‘ab+’/’a+b’ Write , read and Both reading and writing operations can be
append performed.
If the file does not exist file will be created.
If the file exist then the file pointer will go the
end of the file and new content will be
appended.
FILE HANDLING
dump(f,l) is used in the following manner to write the content to the file.

def writefile_list():
fw=open("cloth.dat","ab")
n=int(input("how many records"))
l=[0 for i in range(n)]
for i in range(n):
l=[]
cid=int(input("enter the cloth id"))
cnm=(input("enter fabric"))
cprice=float(input("accept price"))
l.extend([cid,cnm,cprice])
pickle.dump(l,fw)
fw.close()
FILE HANDLING
OUTPUT:-

enter the choice1


how many records 2
enter the cloth id 100
enter fabric cotton
accept price 398.87
enter the cloth id 400
enter fabric linen
accept price 897.67
FILE HANDLING
Load(f) is used to read content from the file. Load() function will raise
EOFError once the end of the file is reached. This error can be handled in 2
ways.
1.USING WITH BLOCK
The file should be opened in read mode using with block .When the file is
opened using with block the programmer does not require to close it. The
moment the control comes out of the with block , the file is automatically
closed and also will be able handle the errors.

So the with block will be responsible for opening the file, closing the file
and also comes with inbuilt error handling capabilities.
FILE HANDLING
def readfile_list():
with open("cloth.dat","rb")as f:
while True:
r=pickle.load(f)
for i in r:
print(i)
FILE HANDLING
Output:-
100
cotton
398.87
400
linen
897.67
r=pickle.load(f)
The inbuilt error handling will throw this error
EOFError: Ran out of input
FILE HANDLING
using Try catch block in the following manner:

def readfile_list():
f=open("cloth.dat","rb")
while True:
try:
r=pickle.load(f)
for i in r:
print(i)
except EOFError:
sys.stderr.write("end of the file reached")
break
f.close()
FILE HANDLING
OUTPUT:
100
cotton
398.87
400
linen
897.67
end of the file reached
FILE HANDLING
Two exceptions that the programmer may
encounter while handling pickle pacakage:-
1.Pickling error:-This error occurs when the
programmer is trying to write unpicklable
object.
2.Unpickling error:-This kind error occurs
while reading the file which was corrupted
and access permission is denied.
FILE HANDLING-BINARY FILES
DIFFERENT MANIPULATIONS THAT CAN BE PERFORMED ON BINARY FILES

1.WRITING TO FILE
2.READ FROM THE FILE
3.COUNT RECORDS
4.SEARCH RECORDS
5.DELETE RECORDS
6.UPDATE RECORDS
7.SORT RECORDS
FILE HANDLING-CSV FILES
CSV files are a kind of delimited file , in which
data is stored in rows and columns and values
are separated by comma while storing.

CSV package is required to import for


handling csv files.
FILE HANDLING
The syntax for opening the csv file is as
follows:

f=open(“stud.csv”,”w”,newline=‘’”)
In the above statement, csv file named
stud.csv is opened for writing and newline is
specified as null to suppress EOL
translations.
FILE HANDLING
Once the csv file is created, we can open the file to
view the data.

We can also view the data opening the same file in


excel.

When these files are opened in a different platforms


there may be errors while reading the file as EOL
character is different for different platform.

To suppress problems encountered on account of EOL


new line character should set as “”(null)
FILE HANDLING
f=open(“stud.csv”,”w”,newline=‘’”) if the programmer does not write new line at the
writing the file then lineterminator=‘\n’ can passed as parameter to the writer function at
the time of creating writing object using csv package in the following manner

fw=csv.writer(f, lineterminator=‘\n’,delimeter=‘|’)-in this line writer object is created.


Where f is the file handle and lineterminator is used for informing the interpreter
specifying its new line so that empty record will not be inserted into the file.

Delimiter is the to explicitly to provide your choice of the separator of various data of the
same record in the place of default “,”

The role of the writer object is to convert the input\data into csv writable delimited form.

If delimiter is not provided by default it will take “ , “


FILE HANDLING
f=open(“stud.csv”,”w”,newline=‘’)
fw=csv.writer(f,delimeter=‘|’)
fw.writerow(l)
Writerow()- This function is used to write one row
to file at a time.
Writerows()-this function is used to write more
than one row at a time.
FILE HANDLING-CSV FILES
DIFFERENT MANIPULATIONS THAT CAN BE PERFORMED ON BINARY FILES

1.WRITING TO FILE
2.READ FROM THE FILE
3.COUNT RECORDS
4.SEARCH RECORDS
5.DELETE RECORDS
6.UPDATE RECORDS
7.SORT RECORDS
FILE HANDLING
When you fetch the content from csv file and display it on screen you can see
along with record empty list also printed in the following manner.

['id', 'item name', 'item price', 'item quantity']


[]
['6000', 'NUTS', '40', '400']
[]
['3000', 'GEAR', '30', '300']
[]
['10000', 'BOLTS', '20', '200']
[]
FILE HANDLING

csv files are also text files. The default EOL


character in windows operating system is ‘\r\n’.
So while reading content from file it reads
records and also reads ‘\r\n’ that is why we are
getting empty list.
FILE HANDLING
This is can be avoided in 2 ways.
When file is opened for writing , the programmer
can provide lineterminator/newline=“”(which
means none”) in the following way so that the
entry of special EOL i.e ’\r\n’ can be avoided.
At the time reading it will not print empty row as
EOL suppressed by setting newline to none.
FILE HANDLING
csvfilew = open(“item.csv”,'w')
If the programmer does not specify newline character at the
time of writing the content to the file , then at the time of
opening file for reading the EOF character of the OS should
be specified as shown below
with open(“item.csv,'r',newline='\r\n')as csvfiler:
If file is created in the following manner without newline
argument.
with open(“item.csv”,‘w')as csvfilew:
with open(“item.csv,'r',newline='\r\n')as csvfiler:
FILE HANDLING
• import sys
• Using sys package , the programmer can
accept values , print values on the screen and
error can be printed in red color in the output
screen.
• st=sys.stdin.readline()—is used to read the
line and assign it st variable.
FILE HNDLING

• st=input("accept the string")


• print(st)
• print("using sys.stdin")
• st=sys.stdin.readline()
• print(st)
FILE HANDLING

For printing the value that is assigned to st can


be printed using sys.stdout.write in the
following the manner

print("using std.out")
sys.stdout.write(st)
FILE HANDLING

• Sys.stderr.write()-is to used to print the error


in the correct way.

• print("no error found")


• sys.stderr.write("no error found")
FILE HANDLING
output_:-
• accept the stringhello
• hello
• using std.in
• how are you
• how are you

• using std.out
• how are you
• no error found
• no error found
FILE HANDLING
• ABSOLUTE PATH:- this specifies the path from
the root directory to the present directory
where the programmer wants to create the
file or folder

• Fn=open(“F:\python\file\modes.txt”)—
absolute path
FILE HANDLING
• RELATIVE PATH:-This specifies the drive ,
folder or subfolder where the programmer
intends to create the folder or file
• Fn=open(“F:\..\..\modes.txt”)—relative path
• In the above syntax the programmer is
creating the file being in the file sub folder of
python main folder which in f: drive and
creating the file in the f:\ drive.

You might also like