You are on page 1of 22

Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.

com

Chapter-6: File Handling


File Handling -> Text File
In this tutorial we will discuss the following topics

S.No. Topics

1 Python: File Handling

2 File Processing

3 DATA FILES

4 How to open file in different modes?

5 Closing Files in Python

6 How to write file?

7 How to read file?

8 How To Read a Text File Line by Line Using an Iterator in Python?

9 Appending data (Inserting Data at the end of the file)

10 Modification/ Updation in Data File (Replace String in File)

11 Copying a file

12 Deleting Data from file

13 Standard input /output and error streams

14 seek() method

Page 1 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


Python: File Handling
 Until now, the Python programs you've been writing use pretty simple input
and output

– User types input at the keyboard

– Results (output) are displayed in the console

 It is good for small and simple input…

– But what if we want to make the annual performance record of 50


students, once we entered all performance details like name, marks and
other details etc. it will displayed output on screen. But if we want to use
again…..

– Start all over???

– So we need file handling to save data somewhere on system for future


use.

What is file?
 A file is a collection of related records stored on a particular area of the
storage medium or device.
Need for File Handling:
 To Store data in organized manner
 To store data permanently
 To access data faster
 To Search data faster
 To easily modify data later on

Page 2 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


File Processing
 In order to do interesting things with files, we need to be able to perform certain
operations:
– Associate an external file with a program object
 Opening the file
– Manipulate the file object
 Reading from or writing to the file object
– Close the file
 Making sure the object and file match at the end

DATA FILES
Python Data Files can be of two types
1) Text File 2) Binary File

Text File:
 Text files are structured as a sequence of lines, where each line includes a
sequence of characters.
 Each line is terminated with a special character, called the EOL or End of
Line character. In python EOL is ‘\n’ or ‘\r’ or combination of both
Binary File

 In this type of file, there is no terminator for a line and the data is stored after
converting it into machine understandable binary language.
 Operations on binary files are faster as no translation required.
 Image files such as .jpg, .png, .gif, etc., and documents such as .doc, .xls, .pdf,
etc., all of them constitute binary files.

Page 3 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


Some of the most common access modes are listed below:
Text File Binary File
Use Description
Mode Mode
This is the default mode. It Opens file for reading.
‘r’ ‘rb’ Read only
File must exists, otherwise Python raises I/O errors
This Mode Opens file for writing.
Write
‘w’ ‘wb’ If file does not exist, it creates a new file.
only
If file exists it truncates the file.
File is in write mode only, new data will be added
‘a’ ‘ab’ Append to the end of existing data i.e. no overwriting. If
file not exists it creates a new file
‘r+b’
Read and File must exists otherwise error is raised Both
‘r+’ or ‘
write reading and writing can take place
rb+’
‘w+b’
Write and File is created if not exists, if exists data will be
w+ or ‘
read truncated, both read and write allowed
wb+’
‘a+b’
Write and Same as above but previous content will be
‘a+’ or
read retained and both read and write.
‘ab+’
Opens a file for exclusive creation. If the file
‘x’ ‘xb’ Write
already exists, the operation fails.
Similar to w+ as it will create a new file if the file
Write and
‘x+’ ‘xb+’ does not exist. Otherwise, will raise
read
FileExistsError.

Text file
r r+ w w+ a a+ x x+
Modes
Binary file
rb rb+ wb wb+ ab ab+ xb xb+
Modes
Read ✔ ✔ ✘ ✔ ✘ ✘ ✘ ✔
Write ✘ ✔ ✔ ✔ ✔ ✔ ✔ ✔
Creates file ✘ ✘ ✔ ✔ ✔ ✔ ✔ ✔
Erases file ✘ ✘ ✔ ✔ ✘ ✘ ✘ ✘
Initial Start Start Start Start End End Start Start
position
Page 4 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


We can do following tasks/operations with python Data File
a) Creation/Opening of an existing Data File
b) Reading from file
c) Writing to Data File
d) Appending data ( inserting Data at the end of the file)
e) Inserting data (in between the file)
f) Deleting Data from file
g) Copying a file
h) Modification/ Updation in Data File.
Syntax for open () Function

MyFile = open ( File_name [, access_mode])

file_name
 File_name is a mandatory argument that you have to provide to
the open function
 While rest all arguments are optional and use their default values.
 To put it simply, the file argument represents the path where your file resides
in your system.
access_mode (optional argument)

MyFile = open (file_name [, access_mode ])


 This argument is a string that determines which of the modes the file is to be
opened in

Page 5 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


How to open file in different modes?
Syntax:
file_object = open (filename) Relative or Absolute path
OR to the file (including the
file_object = open (filename, mode) extension)

A Variable that will A string (Character) that indicates


store the file object what you want to do with the file

Example 1: Open a file in read mode


MyFile = open ("Story.txt", ‘r’) # the relative path is "Story.txt"

Only contains the name of the file. This can be used when the file that you are trying
to open is in the same directory or folder as the Python program resides/ saves.
Example 2: Open a file in write mode
Myfile = open("D:\Amjad_CS\Story1.txt",‘w’)# specifying full path

If the file is within a nested folder, like this:

The Story1.txt file is in the "Amjad_CS" folder

Then we need to use a specific path to tell the function that the file is within
another folder.

Example 3: Open a file in append mode


Myfile = open (r "D:\Amjad_CS\Story2.txt", ‘a’)

The ‘r’ makes the string raw, that is, it tells that the string is without any special
characters. The ‘r’ can be ignored if the file is in same directory and address is not
being placed.

Page 6 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


Closing Files in Python
 close() function closes the file and frees the memory space acquired by that file

 Once we are done with our file, we close it

– We do this for all files – ones that we opened for writing, reading, or
appending or

– If it is to be opened in a different file mode.

myFileObject .close()

 Properly closing the file is important – because

– It ensures that the file is saved correctly

– at the time when the file is no longer needed

Example: Opening and Closing a file "Story1.txt" for object name Myfile.
Myfile = open ("D:\Amjad_CS\Story1.txt",‘w’)
Myfile. close()

How to write file?


 In order to write into a file in Python, we need to open it in write ‘w’,
append ‘a’ or exclusive creation ‘x’ mode.
We have two methods for writing data into a file as shown below.

1. write()

2. writelines(list)

Page 7 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


1. write ( ) method:
 Write can only take one string at a time!
 These won’t work:
fileObj.write("hello", "my", "name")
fileObj.write(17)
 But this will:
fileObj.write("hello" + " my " + "name")
 The write() method returns the number of characters written.

Example: Writes the String ‘Hello Python’ into the ‘learnpython4cbse.txt’ file.

Example: The first line will be ‘Hello Python’ and as we have mentioned \n
character, the cursor will move to the next line of the file and then write ‘Learn
with fun’ with new line character \n and in third line write ‘Python Magic’

Note: Remember if we don’t mention \n character, then the data will be written
continuously in the text file like ‘Learn with funPython Magic’

Page 8 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


2. writelines() :
If you want to write several lines at once, you can use the writelines() method,
which takes a list of strings. Each string represents a line to be added to the file.

The lines are added to the end of the file:

Page 9 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


How to read file?
There are three different ways to read in a file:

1. .read(size):
This reads from the file based on the number of size bytes. If no argument is passed
or None or -1 is passed, then the entire file is read.

Syntax: fileObj.read(size)
Example: Read and print the entire file “learnpython4cbse.txt”

OUTPUT:

Example: Read and print the first 5 character from a file


OUTPUT

Page 10 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


2. .readline(size)
 This reads at most size number of characters from the line.
 This continues to the end of the line and then wraps back around.
 If no argument is passed or None or -1 is passed, then the entire line (or rest of
the line) is read.

Example: Read and print the entire file line by line

CODING OUTPUT

Example: Read and print the first 20 character of second line from a file
using readline( ) method
CODING OUTPUT

3. .readlines(size)
 It is used to read all the lines at a single go and then return them as each line a
string element in a list.
Page 11 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


Example: Read and Get list of all lines of a file

OUTPUT:

How To Read a Text File Line by Line Using an Iterator in Python?


1. How To Read a Text File Line by Line Using While Statement in Python?

Example 1: Use the readline() to read further. If the file is not empty
keep reading one line at a time, till the file is empty
TYPE -1 TYPE -II

OR

Page 12 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


Example 2: Instead of reading them manually, use a “for loop” to iterate
through the file line by line.

Example 3: Use the readlines() to read file line by line

2. Read file line by line with context manager


Use of ‘with’ block
 The with statement automatically takes care of closing the file once it leaves
the with block, even in cases of error.
 As it is highly recommend that you use the with statement as much as possible,
as it allows for cleaner code and makes handling any unexpected errors easier
for you.

Page 13 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


 the above examples (1-3) can be further simplified by iterating over the file
object itself:

OUTPUT: The output is same for all examples (1-3) and use of with
block

So, you can Read a Text File Line by Line using any one of the methods as we
discussed above.

Page 14 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


Appending data (Inserting Data at the end of the file)
In order to append a new line to the existing file, open the file in append mode, by
using either 'a' or 'a+' as the access mode.

Example: Append display new student details in existing file.

Variable length tuple parameter which


can accept n variables during function
calll

File open in append mode i.e. records


can be added at the end of file

Writing a record into a file

Open a file and iterate line by line to


display

Accept the value of sname, sperc and


remarks from user

Calling a function Writerrecord() to


write the values into a file

Calling of function Input( ) to enter


student’s details by user

Calling a function Readrecord( ) to


display student’s details .

Page 15 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


OUTPUT:

New Record is appended at


the end of the file

Modification/ Updation in Data File (Replace String in File)

1. Open StudentRecord.txt in
read text rt mode and get the
reference to fileRead.
Open NewStudentRecord.txt in
write text wt mode and get the
reference to newfile

for line in fileRead : for each line


in fileRead i.e., StudentRecord.txt,
line.replace(): replaces
string pyton with python and
newfile. write: writes to out.txt.

Calling of Modify function with arguments


(“Amit”,”Aman”) where, Amit has to be replaced
with Aman

Page 16 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


OUTPUT:

As Shown in output, Student Name

Amit is replaced with Aman

In the following example, we will replace the string Ahil with ashaz in
StudentRecord.txt file, and overwrite the StudentRecord.txt file with the replaced
text.

Page 17 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


Copying a file

Example: The program copies the contents of one file and writes it into another.

Steps to follow:

1. Open one file called StudentRecord.txt in read mode.


2. Open another file Copystudentecord.txt in write mode.
3. Read each line from the input file and write it into the output file.

Deleting Data from file

Steps to follow:

 Open file in read and write mode, get all the data from the file and close it. OR
open file in with block in read and write mode.

 Read the content in new_f object and compare with the given string

Page 18 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


 Example: The below given code delete the record of student “Amit” from the
file “StudentRecord.txt”

OUTPUT:

Page 19 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


Standard input /output and error streams

In Python, the sys.stdin, sys.stdout, and sys.stderr are file-like objects that can
perform expected operations like read() and write()

STANDARD OUTPUT

print(x) is basically a shortcut for sys.stdout.write(x + '\n')

import sys

# Standard output - sys.stdout

print(type(sys.stdout))

sys.stdout.write('Hello\n')

STANDARD ERROR

Standard error works just like standard output and can be used the same way.
Standard error has file descriptor 2 where standard output has file descriptor 1. This
is beneficial if you want to separate warning and error messages from the actual
output of your application. For example, if your program outputs an XML file, you
don't want error strings injected in the middle of your XML file.

# Standard error - sys.stderr

print(type(sys.stderr))

sys.stderr.write("Error messages can go here\n")

To pipe standard error from the shell to a file while leaving standard output going to
the terminal.

Page 20 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


STANDARD INPUT
Standard input defaults to your keyboard in the terminal, but you can also pipe in
files or the output from a previous program to your standard input. Here is a basic
example of reading one byte from standard input:

# Standard input - sys.stdin

print(type(sys.stdin))

letter = sys.stdin.read(1) # Read 1 byte

print(letter)

# Can also do things like `sys.stdin.readlines()`

If you want interactive input from the user, it is better to use input() instead of
sys.stdin.read() when asking for user input

Note : (Reference for standard stdout,sdtin and sdterr-> https://www.devdungeon.com)

Page 21 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-6: File Handling


seek() method

To read or write at a specific position, use the seek() function to set the current
read/write position.

Syntax: f.seek(offset, from)

Here, the from parameter takes the following values:

 0 : offset calculated from the beginning


 1 : offset calculated from the current position
 2 : offset calculated from the end

Assuming that myfile.txt contains " Python is a widely used general-purpose" text,
the following example demonstrates the seek() method.

The output of the above example is " is a widely used general-purpose ".

Page 22 of 22

You might also like