File Handling New
File Handling New
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
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 writing only. Overwrites the file if already exists,else creates a new file
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.
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
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”)
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()