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

Text Files - File Handling

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Text Files - File Handling

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

Computer Science

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.

• A file is a collection of related data stored in


computer storage for future data retrieval.

• File is created for permanent storage of data.


File Handling
Need For A Data File
• In programming, Sometimes, it is not enough to only display the
data on the console. Those data are to be retrieved later on,then
the concept of file handling comes. It is impossible to recover the
programmatically generated data again and again.

• However, if we need to do so, we may store it onto the file system


which is not volatile and can be accessed every time. Here, comes
the need of file handling in Python.
File Handling
• File handling refers to reading and writing contents
from a file.

• File handling in Python enables us to create, update,


read, and delete the files stored on the file system
through our python program. The following
operations can be performed on a file.

• In Python, File Handling consists of following three steps:


➢ Open the file.
➢ Process file i.e. perform read or write operation.
➢ Close the file.
File Handling
Types of File
There are three types of files:

1. Text Files

2. Binary Files

3. CSV(Comma Separated Values) Files


File Handling
Text Files
• Text files are structured as a sequence of lines, where each line
includes a sequence of characters

• A file whose contents can be viewed using a text editor is called a


text file.

• A text file is simply a sequence of ASCII or Unicode characters.

• Python programs, contents written in text editors are some of the


example of text files.
File Handling
Binary Files
• A binary file is any type of file that is not a text file.

• 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.

• We can’t read a binary file using a text editor.


File Handling
CSV(Comma Separated Values) Files
• CSV (Comma Separated Values) is a simple file format used to store tabular
data, such as a spreadsheet or database.

• 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.

Developed for an application and can


Widely used file format and can be
be opened in that application only.
opened in any text editor.
Mostly .txt and .rtf are used as Can have any application defined
extensions to text files. extension.
File Handling
Opening and Closing A File
• To perform file operation ,it must be opened first then after
reading,writing, editing operation can be performed.

• To open a file, Python provide built in function open() for it.

• open( ) function returns a file object.

• Syntax
file object = open(<file_name>)

file object = open(<file_name>, <access_mode>)

file_name - Name of the file ,enclosed in double quotes.


access_mode- Determines the what kind of operations can
be performed with file, like read, write etc.
File Handling
open Function-
Example1: file1 = open("book.txt“)

The above statement opens the file “book.txt” in file mode as read
mode(default mode) and attaches it to file object namely file1.

Example2: file2=open(“demo.txt”, ”r”)

The above statement opens the file “demo.txt” in file mode as


read mode(because of “r” give as mode) and attaches it to file
object namely file2.
File Handling
open Function-

Example3: file3 = open(“e:\\PythonFiles\\book.txt“, “r”)

The above statement opens the file “book.txt”(stored in the folder


E:\PythonFiles) in read mode and attaches it to file object namely
file3.

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.

• It is used to obtain a reference to a file.

• Its is also called a file-handle.

• All the functions that we perform on a data file are performed


through the file handle.

• 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:

with open(“filename”) as file_object:

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”, “w”) as f:


f.write(“Hello World”)

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.

• Read, write or for appending etc.

• This is informed to the Python interpreter by using the various


file modes.
File Handling
File opening modes-
Sr. Mode & Description
No
.
1 r - reading only.Sets file pointer at beginning of the file . This is the defaultmode.
2 rb – same as r mode but with binary file
3 r+ - both reading and writing. The file pointer placed at the beginning of the file.
4 rb+ - same as r+ mode but with binary file
5 w - writing only. Overwrites the file if the file exists. If not, creates a new file for writing.
6 wb – same as w mode but with binary file.
7 w+ - both writing and reading. Overwrites . If no file exist, creates a new file for R &W.
8 wb+ - same as w+ mode but with binary file.
9 a -for appending. Move file pointer at end of the file.Creates new file for writing,if not exist.
10 ab – same as a but with binary file.
11 a+ - for both appending and reading. Move file pointer at end. If the file does not exist, it creates
a new file for reading and writing.

12 ab+ - same as a+ mode but with binary mode.


File Handling
The close() Method

• close() function is used to close an opened file.

• 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

Basic operations with files:

a. Read the data from a file


b. Write the data to a file
c. Append the data to a file
d. Delete a file
File Handling
Reading from Files
There are 3 types of functions to read data from
a file.

1. read( n ) : reads at most n bytes. if no n is


specified, reads the entire file.

Returns the read bytes in the form of a string.


File Handling
Reading from Files
2. readline( ) : Reads a line.

readline([n]): if n is specified, reads n bytes.

Returns the read bytes in the form of a string


ending with ln(line) character or returns a blank
string if no more bytes are left for reading in the
file.

NOTE: A line is considered till a new line(EOL)


character is encountered.
File Handling
Reading from Files

3. readlines( ): Reads all lines and returns a


list containing the lines that are read.
File Handling
Steps to Read data from a file

• Create and Open a file using open( ) function

• use the read( ), readline( ) or readlines( )


function

• print/access the data

• Close the file.


File Handling
Reading from Files

Let a text file “Book.txt” has the following text:

“Python is interactive language.


It is case sensitive language.
It makes the difference between uppercase and lowercase letters.
It is official language of google.”
File Handling
Reading from Files using read()
Example : Write the Python code to read
the file “Book.txt” using read() function.
fin=open("Book.txt",'r’) fin=open("Book.txt",'r’)
str=fin.read( ) str=fin.read(10)
print(str) print(str)
fin.close( ) fin.close( )

OUTPUT: Python is interactive language. It OUTPUT:


is case sensitive language. Python is
It makes the difference between uppercase
and lowercase letters.
It is official language of google.
File Handling
Reading from Files using readline()
Example : Write the Python code to read the
first line of the file “Book.txt” using readline()
function.

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:

“Python is interactive language.


It is case sensitive language.
It makes the difference between uppercase and lowercase letters.
It is official language of google.”

Output :
Python is interactive language.

It is case sensitive language.

It makes the difference between uppercase and lowercase letters.


File Handling
Reading from Files using readline()
• readline() functions reads the newline character
(‘\n’) also while reading the line.

• This newline character gets inserted by print


statement in the output.

• So that’s why is shows a blank line between the


lines printed in the output.
File Handling
Reading from Files using readline()
• This can be avoided in two ways:
(i) use end=‘ ‘ -so that print does not put any additional
newline character.
fin=open("Book.txt",'r')
str=fin.readline( )
print(str)
str=fin.readline( )
print(str, end=‘ ‘)
str=fin.readline( )
print(str, end=‘ ‘)
fin.close( )

(ii) use strip(): strip() function removes all the leading


and trailing spaces,tabs or newline characters.
fin=open("Book.txt",'r')
str=fin.readline( )
print(str.strip())
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” line by line.

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.

Q: Write the Python code to display the


number of lines in the file “Book.txt” .

Q: Write the Python code the number of


words in the file “Book.txt” .

Q: Write the Python code the number of


vowels in the file “Book.txt” .
File Handling
Reading from Files
Q: Write the Python code to count the
number of words starting with a vowel in
the file “Book.txt” in Bytes.

Q:Write the codeCount the number of ‘is’


word in file “Book.txt” file.

Q. Write a python code to find the size of


the file in bytes, number of lines and
number of words.
File Handling
Reading from Files
Q. Write a python code to find the size of the file
in bytes, number of lines and number of words.

Q Write code to print just the last line of a text file


“Book.txt”.

Q Write a function in Python to count and display the


number of lines starting with alphabet ‘P’ present in a
text file “Book.TXT”.
CBSE QUESTION PAPER QNO 4
CBSE QUESTION PAPER 2015 Delhi
CBSE QUESTION PAPER 2015 Delhi
4(a) Differentiate between the following : 1
(i) f = open(‘diary.txt’, ‘r’)
(ii) f = open(‘diary.txt’, ‘w’)

4(b) Write a method in python to read the content


from a text file diary.txt line by line and display the
same on screen. 2
CBSE QUESTION PAPER 2016 Delhi
CBSE QUESTION PAPER 2016 Delhi

4. (a) Write a statement in Python to perform


the following operations : 1

✓ To open a text file “BOOK.TXT” in read mode


✓To open a text file “BOOK.TXT” in write
mode

4(b) Write a method in python to read the


content from a text file diary.txt line by line
and display the same on screen. 2
CBSE QUESTION PAPER 2017 Delhi
CBSE QUESTION PAPER 2017 Delhi

4 (a) Differentiate between file modes r+ and rb+ with


respect to Python. 1

4(b) Write a method in Python to read lines from a text


file MYNOTES.TXT, and display those lines, which are
starting with the alphabet K 2
CBSE QUESTION PAPER 2018 AI
CBSE QUESTION PAPER 2018 AI

4 (a) Write a statement in Python to open a text


file STORY.TXT so that new contents can be
added at the end of it. 1

4 (b) Write a method in Python to read lines from


a text file INDIA.TXT, to find and display the
occurrence of the word ‘‘India’’. 2

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.

The whole world is looking at India as a great


market.
Most of the Indians can foresee the heights that
India is capable of reaching.’’

The output should be 4. 2


File Handling
Writing onto Files
There are 2 types of functions to write the data to
a file.

1. write( n ) : writes data to the file.

Synatx : <filehandle>.write(str)

writes string str to file referenced by


<filehandle>.
File Handling
Writing onto Files
There are 2 types of functions to write the data to
a file.

2. writelines( n ) : writes data to the file.

Synatx : <filehandle>.write(L)

writes all the strings in list L to file referenced


by <filehandle>.
File Handling
Writing onto Files
File Modes:
• The file access mode used to write onto the file
is “w”.

• When a file is open in ”w” mode, Python


overwrites an existing file or creates a non-
existing file.

• When file is opened in “a” append mode, it


retains the previous data while allowing us to
add new data at the end.
File Handling
Writing onto Files
Example : Write the Python code write some data onto a
file “student.dat”.
file1=open(“student.dat",’w’)
for i in range(5):
name=input(“Enter a name”)
file1.write(name)
file1.close()

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.

• It doesn’t overwrite the existing data in a file.

• To write the data in the end of the file, you have to


use the following mode:

"a" - Append - will append to the end of the file.


File Handling
Writing onto Files
Q. Write the Python code to add details of two more students
in the above created file.
File Handling
File access modes
(i) In an existing file while retaining its content.
(a) If the file has been opened in append mode (“a”) to
retain the old content.
(b) If the file has been opened in “r+” or “a+” mode to
allow reading as well writing.

(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.

• flush() function is used to flush the internal buffer.


• Python automatically flushes the files when closing them,
i.e. This function is implicitly called by the close()
function.

• But we may some time want to flush the data before


closing any file.

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

fin = open("dummy.txt", "r")


data = fin.read()
data = data.replace(‘my', ‘your’)
fin.close()

fin = open("dummy.txt", "w")


fin.write(data)
fin.close()
File
Handling Methods of os module
File system related methods available in os module(standard
module) which can be used during file operations.
1. The rename() method used to rename the file.
e.g.program
Syntax os.rename(current_file_name, new_file_name) import os
2.The remove() method to delete file. print(os.getcwd())
Syntax os.remove(file_name) os.mkdir("newdir")
3.The mkdir() method of the os module to os.chdir("newdir")
create directories in the current directory. print(os.getcwd())
Syntax os.mkdir("newdir")
4.The chdir() method to change the current
directory. Syntax os.chdir("newdir")
5.The getcwd() method displays the current directory.
Syntax os.getcwd()
6. The rmdir() method deletes the directory.
Syntax os.rmdir('dirname')
File Handling
Modifying a Text File
Replace string using temporary 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

All reading and writing functions


discussed till now, work sequentially in the file.
To access the contents of file randomly –
following methods are use.

seek method

tell method
seek method

seek()method can be used to position the


file object at particular place in the file.
It's syntax is :

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

Value reference point

0 beginning of the file (for text files and binary files)


1 current position of file (works for binary files only)
2 end of file (works for binary files only)

default value of from_what is 0, i.e. beginning


of the file.
seek method

f.seek(7) keeps file pointer at 7th byte reads


the file content from 8th position
onwards to till EOF.
Reading according to size

In the input function if you specify the


number of bytes that many number of bytes
can be fetched and assigned to an identifier.
Reading according to size

f.read(1) will read single byte/ character


starting from byte number 8. hence byte
number 8 is P so one character/byte is fetched
and assigned to f_data identifier.
Reading according to size

f.read(2) - will read 2 chars/bytes


f.read(4) - will read 4 chars/bytes

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

tell() method returns an integer and


assigned to pos variable. It is the current
position from the beginning of file.
File Handling
Standard Input ,Output and Error Stream
• Keyboard is a standard input and monitor is a standard
output device and errors are also displayed on monitor
so monitor is a standard error device also.

• Standard devices can also be used

• These devise are also implemented as files in python


called standard streams.

• These streams can be used by using sys module.


File Handling
Standard Input ,Output and Error Stream

Some Standard Streams in python are as


follows –
• Standard input Stream sys.stdin
• Standard output Stream sys.stdout
• Standard error Stream sys.stderr
File Handling
Standard Input ,Output and Error Stream
Example
import sys
f=open("hello.txt")
line1=f.readline()
line2=f.readline()
line3=f.readline()
sys.stdout.write(line1)
sys.stdout.write(line2)
sys.stdout.write(line3)
sys.stderr.write("\n No errors occurred \n")
f.close()

OUTPUT: Comp Science


Informatics Practices
File Handling
No errors occurred
File Handling
Relative and Absolute Paths
• We all know that the files are kept in directory which are also
known as folders.
• Every running program has a current directory. Which is generally a
default directory and python always see the default directory first.
• The absolute paths are from the topmost level of the directory
structure.
• The relative paths are relative to the current working directory
denoted as a dot(.) while its parent directory is denoted with two
dots(..).
• OS module provides many such functions which can be used to
work with files and directories. OS means Operating System.
• getcwd( ) is a very function which can be used to identify the
current working directory
>>> import os
>>> cwd=os.getcwd()
>>> print(cwd)
C:\Users\kv2kkdSrSec\AppData\Local\Programs\Python\Python36-32
ABSOLUTE PATH

Absolute path of file is file location, where


in it starts from the top most directory

ABSOLUTE PATH
RELATIVE PATH

Relative Path of file is file location, where


in it starts from the current working directory

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)

You can combine open() with the file-object’s function, if


you need to perform just a single task on the open file in
following way:

>>>open(“book.txt”, “r”).read(30)

You might also like