File Handling 1
File Handling 1
File Handling 1
\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
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
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=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
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:-
‘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.seek(-4,0)-not possible
FILE HANDLING-BINARY FILES
The binary files are stored with .dat extension or any application
defined extension.
The content of the binary is not readable as the data is not stored
in the form of ASCII
‘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:-
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.
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.
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.
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.
print("using std.out")
sys.stdout.write(st)
FILE HANDLING
• 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.