Text Files - File Handling
Text Files - File Handling
Class XII
File Handling
File Handling
What is a File?
• A file is a sequence of bytes on the
disk/permanent storage where a group of
related data is stored.
1. Text Files
2. Binary Files
• A binary file stores the data in the same way as stored in the
memory.
• The .exe files,mp3 file, image files are some of the examples of
binary files.
• A CSV file stores tabular data (numbers and text) in plain text. Each line of
the file is a data record. Each record consists of one or more fields, separated
by commas.
• The use of the comma as a field separator is the source of the name for this
file format.
• For working CSV files in python, there is an inbuilt module called csv.
File Handling
TEXT FILES BINARY FILES
Stores information in ASCII characters. Stores information in the same format
which the information is held in memory.
Each line of text is terminated with a special No delimiters are used for a line.
character known as EOL (End of Line)
Some internal translations take place when No translation occurs in binary files
this EOL character is read or written.
Slower than binary files. Binary files are faster and easier for a
program to read and write the text files.
Store only plain text in a file. Can store different types of data
(audio, text, image) in a single file.
• Syntax
file object = open(<file_name>)
The above statement opens the file “book.txt” in file mode as read
mode(default mode) and attaches it to file object namely file1.
If just the file name is given, then Python searches for the file in
the current folder.
File Handling
FILE OBJECT
• File objects are used to read and write data to a file on disk.
• So, when we use OPEN() ,python store the reference of the file
in the file object.
• EXAMPLE: file1, file2, file3 used in the above examples are the
file object(or file handle) that are storing the reference of a
particular file mentioned in the open function.
File Handling
Open Function
With Statement
One bonus of using this method is that any files opened will be closed
automatically after you are done. This leaves less to worry about during cleanup.
To use the with statement to open a file:
EXAMPLE:
with open(“testfile.txt”) as fin:
data = fin.read()
print(data)
File Handling
Open Function
Examples:
with open(“testfile.txt”) as f:
for line in f:
print line
with open(“hello.txt”) as f:
data = f.readlines()
File Handling
FILE ACCESS MODES
• When Python opens a file, it needs to know how the file will be
used.
• After using this method,an opened file will be closed and a closed file
cannot be read or written any more.
E.g. program
File1=open("book.txt",'a+’)
______
_______
file1.close()
File Handling
Working with Text Files
fin=open("Book.txt",'r')
str=fin.readline( )
print(str)
fin.close( )
OUTPUT:
Python is interactive language.
File Handling
Reading from Files using readline()
Example : Write the Python code to read the first three
lines from the file “Book.txt” using redline() function.
fin=open("Book.txt",'r')
str=fin.readline( )
print(str)
str=fin.readline( )
print(str)
str=fin.readline( )
print(str)
fin.close( )
File Handling
Reading from Files using readline()
Let a text file “Book.txt” has the following text:
Output :
Python is interactive language.
fin=open("Book.txt",'r')
str=“ “
while str :
str=fin.readline( )
print(str.strip())
fin.close( )
File Handling
Reading from Files using readline()
Example : Write the Python code to read complete file
“Book.txt” using file handle..
fin=open("Book.txt",'r’)
for str in fin:
print(str.strip())
fin.close( )
File Handling
Reading from Files
Example : Write the Python code to read the file
“Book.txt” using readlines() function.
fin=open("Book.txt",'r’)
LI=fin.readlines( )
print(L1)
fin.close( )
OUTPUT:
['Python is interactive language .’\n’,
It is case sensitive language.’\n', 'It makes the difference between
uppercase and lowercase letters.’\n', 'It is official language of google. .’\n']
File Handling
Reading from Files
Q: Write the Python code to read display
the size of the file “Book.txt” in Bytes.
For example :
If the content of the file is
‘‘India is the fastest growing economy.
CBSE QUESTION PAPER 2018 Delhi
India is looking for more investments around the
globe.
Synatx : <filehandle>.write(str)
Synatx : <filehandle>.write(L)
NOTE: write() function do not add a new line character (‘\n’) after every
write operation so make sure to write the new line characters manually
like the following:
file1=open(“student.dat",’w’)
for i in range(5):
name=input(“Enter a name”)
file1.write(name)
file1.write(‘\n’)
file1.close()
File Handling
Writing onto Files
Example : Write the Python code write some data onto a
file “student.dat” using writelines().
file1=open(“student.dat",’w’)
L1=[ ]
for i in range(5):
name=input(“Enter a name”)
str=name+’/n’
L1.append(str)
file1.writelines(L1)
file1.close()
NOTE: writelines() function also do not add a new line character (‘\n’)
after every write operation so make sure to add it on your own into the
file.
File Handling
Writing onto Files
Q. Write the Python code to take the details (name, roll no
and marks) of a student and store it in the file “student.dat”.
File Handling
Appending data to a Files
• This operation is used to add the data in the end
of the file.
(ii) To create a new file or to write on an existing file after overwriting its
old content
(a) If the file has been opened in write-only mode (“w”).
(b) If the file has been opened in “w+” mode to allow
writing as well as reading.
File Handling
Copying One file into Another
Q.Write a function to copy the content of file “Note.txt” to a
file “Sub.txt”.
Book.txt
File Handling
Copying One file into Another
File Handling
Writing onto Files
Q. Write the Python code to read file “Book.txt” and copy
those lines into file “Notes.txt”which are starting with
alphabet “P”.
File Handling
flush() function
• Python holds everything to write in the file in buffer and
pushes it at a later time.
syntax: <fileobject>.flush()
File Handling
flush() function
Example:
f=open(‘out.log’,’w+’)
f.write(“The output”)
f.write(“my” + “work”)
f.flush()
s=‘ok’
f.write(s)
f.write(“over”)
f.flush()
f.close()
File Handling
Modifying a Text File
Replace string in the same File
import os
f=open("a.txt","r")
g=open("c.txt","w")
for text in f.readlines():
text=text.replace('my','your’)
g.write(text)
f.close()
g.close()
os.remove("a.txt")
os.rename("c.txt","a.txt")
print("file contents modified")
Delete a file
To delete a file, you have to import the os module,
and use remove( )
function.
import os
os.remove("Book.txt")
Check if File exist:
To avoid getting an error, you might want to check if
the file exists before you try to delete it:
Example
Check if file exists, then delete it:
import os
if os.path.exists("Book.txt"):
os.remove("Book.txt")
else:
print("The file does not exist")
RANDOM ACCESS METHODS
seek method
tell method
seek method
fileobject.seek(offset [, from_what])
here offset is used to calculate the position
of fileobject in the file in bytes. Offset is added to
from_what (reference point) to get the position.
Following is the list of from_what values:
seek method
and so on..
tell method
tell() method returns an integer giving
the current position of object in the file. The
integer returned specifies the number of bytes
from the beginning of the file till the current
position of file object.
It's syntax is
fileobject.tell()
tell() method
tell()method
ABSOLUTE PATH
RELATIVE PATH
Myfolder\myfile.txt
RELATIVE PATH
Some Added Features
File Handling
Open Function
File_object=open(name[, mode[, buffering]])
File Buffering in Python: In the builtin open() function, there is an optional
argument, called buffering. This argument is used to specify the file's desired
buffer size i.e.
•1: line buffered
•0: unbuffered
•any other positive value: a buffer of that size in bytes
•negative value: use the system default which is usually line buffered for tty
(teletypewriter) devices and fully buffered for other files. This is default value
of the buffering argument.
A buffer stores a chunk of data from the Operating System's file stream
until it is consumed, at which point more data is brought into the buffer.
The reason that is good practice to use buffers considerable time is taken
to fetch data from it and also to write to it.
File Handling
Open Function
Let's take an example.
Let's say you want to read 100 characters from a file every 2 minutes over
a network. Instead of trying to read from the raw file stream every 2
minutes, it is better to load a portion of the file into a buffer in memory, and
then consume it when the time is right. Then, next portion of the file will be
loaded in the buffer and so on.
filedata = open(file.txt,"r",0)
or
filedata = open(file.txt,"r",1)
EXAMPLE: or
filedata = open(file.txt,"r",2)
or
filedata = open(file.txt,"r",-1)
or
filedata = open(file.txt,"r")
File Handling
Open Function
fin=open(“book.txt”, ”r”)
datastring=fin.read(30)
print(datastr)
>>>open(“book.txt”, “r”).read(30)