Text File Handling in Python Handout

Share with others

Text File Handling in Python Handout is written in a very simple language which can be understood by all students. You will see the QnA session in between the content which will help you to assess yourself.

Table of Content

  1. Text File Handling in Python Handout – Part 1
  2. Text File Handling in Python Handout – Part 2
  3. Text File Handling in Python Handout – Part 3

Text File Handling in Python Handout – Part 1

What is File?

A file is a document which can be read, written according to the requirement. Every File has a unique name. In other words we can say that file is a collection of bytes which is stored in a secondary storage like hard disk, pen drive etc.

Why File?

As file store the data permanently, which can be accessed even after closing the program. Like we create a file in MS word, Power point etc. so that we can access the data later when required.

Types of File: There are two types of file

  1. Text File
  2. Binary File

Difference between Text file and Binary File.

Text FileBinary File
These files can be read by human directlyThese files can not be read by humans directly.
Each line is terminated by a special character ,
known as EOL
No delimiter for a line
Processing of file is slower than binary fileProcessing of file is faster than text file

open( ) and close( ) functions :

The first step to work with a file is to open a file. We can open a file by using open( ) function. open() function takes two arguments.

  1. Name of the file
  2. Access mode

Syntax to open a file

file handle/file object = open(“file name”, “access mode”)

NOTE: By default access mode is read mode

Let we take an example. Suppose there is a file named “data.txt” is to be open for reading then the code will be as follows.

f = open (“data.txt”, “r”)

Explanation of above code :

  1. ‘f’ is file object or file handle ( A file object is reference to file by which we can read and write in file)
  2. open( ) function is used to open a file named “data.txt”
  3. “r” is read mode. In this mode we can read the contents.

Modes for opening a file:

  • Read : This mode is to read the content of the file. It is denoted by symbol “r”
  • Write : This mode is used to write the content on the file. It over writes the previous content. It is denoted by symbol “w”.
  • Append : This mode is used to add the data in the existing content of the file.

Text File Handling in Python Handout (Question Answer Session.)

Q1. What is the difference between the write and append mode?
Q2. f = open("data.txt")
The above file will open in _______________ mode.
Q3. f = open("data.txt", "w")
The above statement will return any error, if the file "data.txt" does not exist.
Q4. What error is returned by the following code, if the file does not exist.
f=open("data.txt", "r")

Types of File Modes

r : open file in read mode. This is the default mode

r+ : open the file in reading and writing mode means we can read the data as well as write the data.

This also return error if file does not exist.

w : This mode will open file in write mode. This mode will create a new file, if file does not exist. This

mode will over writes the existing content.

w+ : This mode open the file in writing and reading mode.

a : This mode will open file in append mode. This mode will add data at the end of the file. The file

pointer is present at the end of the file.

a+ This mode is for both appending content and reading content.

Note :

  • File should be saved in the same folder where python is saved, otherwise we need to give complete path for example if the file “work.txt” store in a folder “senior” in D drive so we can open file in read mode by the following two ways.
    1. f = open(“D:\\senior\\work.txt”,”r”)
    2. f = open(r,”D:\senior\work.txt”, “r”)
  • Giving extension to the file is not mandatory like we can open file f = open (“data”, “r”) will also work

Text File Handling in Python Handout (Question Answer Session.)

Q1. Is there any difference between the following statements?
            f = open("data.txt")    and f = open("data.txt", "r")
Q2. Write the code to open a file "name.txt" which is stored in folder named "demo" 
       in C drive.
Q3. Where  the file pointer present when we open file in the following mode
1. Read mode
2. Write mode
3. Append mode
File Handling – Part 1

Properties of File Object.

A file object or file handle is the reference of a file which helps to do various task on file. It has various properties like:

  1. name : It displays the name of the file
  2. mode : It displays the mode of file(in which mode it is opened)
  3. closed : It displays whether the file is closed or not. It return False if the file is open and True if the file is closed.
  4. readable() : It displays whether the file is readable or not.

for example

File Handling Handout

Output of the above program will be

data.txt
w
False
False

Functions for Reading File:

Reading file help us to play with the character, word or lines of a file. There are many methods or functions in python which help us to read data from file. We will discuss one by one

1. read() : This function is used to read the entire content of file.

for example:

f = open("data.txt", "r")
d = f.read( )

The first line of code will open the file data.txt in read mode and the second line will read the entire content and transfer/store data in variable d in the form of String.

2. read(n) : This function will read the first n character from the file .

for example

f = open("data.txt", "r")
d = f.read(5)

The above code will print the first five character from the file.

Q1. Write the output of the following code 
f = open("data.txt", "r")
d =read()
d1 = read(5)
print(d)
print(d1)

#data file contains the following data
Welcome to csiplearninghub.com

3. readline() : This function will read one line at a time from the file

Syntax of using readline() is

f = open("data.txt", "r")
d = f.readline()
print(d)

The above code will read and print first line from the file. To read the entire content of file, we need to use the loop.

f = open("data.txt", "r")
for i in f:
  print(i)

4. readlines() : This function is used to read all the lines from the file. This method will return a list of strings, each separated by \n.

f = open("data.txt", "r")
d = f.readlines()
print(d)

Text File Handling in Python Handout (Question Answer Session.)

Q1. What is the difference between read() and read(n) function?
Q2. How readline() is different from readlines()?
Q3. Write a program to read the frequency of alphabet 'a' in file.
Q4. Write a program to count the total number of characters in a file.
Q5. Write four properties of file objects.

Solution of Q 3

python file handling handout

Solution of Q 4

python file handling handout

File Handling – Part 2

Text File Handling in Python Handout – Part 2

Writing to File

We can write data into our file with the help of programs in python. When we open file in write mode and file does not exist then this mode will create a new file.

There are two functions in python which help us to write data into a file.

  1. write(string) : This method takes a string as parameter and write the same string into our file. This method does not add EOL (End of Line) character automatically. We have to add ‘\n’ character after each line. This method takes only string as argument so if you want to add numbers in file then first we need to convert the number into string.
f = open("data.txt", "w")
f.write("welcome to my site")
f.write("csiplearninghub.com")
f.close()

Output of the above code

Text File Handling in Python Handout

NOTE : Don’t Forget to write the close() method at the end of the code

To display the above text in separate lines we need to add “\n” at the end of first line.

f = open("data.txt", "w")
f.write("welcome to my site\n")
f.write("csiplearninghub.com")
f.close()

Output of above code

Text File Handling in python handout

Q1. Write a program to accept age from the user and write in a file “data.txt” like below:

“Your age is 34”

Ans. 

f = open("data.txt", "w")
age = input("Enter your age")
f.write("Your age is ")
f.write(age)
f.close()

2. writelines() : This method is used for writing the sequence data type like list, tuple or string into a file.

Syntax of writelines()

f.writelines(sequence)

Q2. Write a program to write names of five friends in a file “data.txt” by using write() as well as writelines() method.

f=open("data.txt","w")
f.writelines(["Amit\n","Sumit\n","Anil\n","Naina\n","Ananya\n"])
f.close()

Output of above program

Amit
Sumit
Anil
Naina
Ananya

Point to remember : If we don’t use “\n” in above program then the names will be displayed in same line.

The above program can also be done by using write() method.

f=open("data.txt","w")
f.write("Amit\n")
f.write("Sumit\n")
f.write("Anil\n")
f.write("Naina\n")
f.write("Ananya\n")
f.close()

Point to remember : When we have to write a list, tuple we will use writelines() instead of write(). For string, we can use any function either write() or writelines().

Text File Handling in Python Handout (Question Answer Session.)

Q1. Write a program to write the following lines in the same format in a file "data.txt" (using write()  
      as  well as writelines() method)

      Welcome to 
      my website
      www.csiplearninghub.com

Q2. What is the difference between write() and writelines() method?
Q3. write mode creates a new file, if file does not exist. (T/F)
Q4. Write a program to accept Roll number and name of five students from the user and write on 
      a file "roll.txt"
Q5. Write a program to find the length(number of characters) of the file "data.txt".

SOLUTIONS

Ans1. 
f=open("data.txt","w")
f.write("Welcome to\n")
f.write("my website\n")
f.write("www.csiplearninghub.com\n")
f.close()

OR

f=open("data.txt","w")
f.writelines(["Welcome to\n","my website\n","www.csiplearninghub.com\n"])
f.close()

Ans2. 
write() method is used to write string in file while writelines() is used to write list in a file.

Ans3. True

Ans4. 
f=open("data.txt","w")
f.write("Roll number")
f.write("\t\t")
f.write("Name")
f.write("\n")
for i in range(5):
rn=input("Enter roll number")
nm = input("Enter name")
f.write(rn)
f.write("\t\t\t")
f.write(nm)
f.write("\n")
f.close()

Execution and output of the above program is shown below

File Handling Part 2                         File Handling Part 2 Output

Ans 5.
f=open("data.txt","r")
d = f.read()
print("Length of file is", len(d))

With Statement

Till now we have done many programs and in each programs we have used the following functions.

  • open()
  • close()

we can close the file without using close() function or we can say that file automatically closed and that can be achieved by using “with” statement.

Demonstration of “with” Statement in the following program

with open("data.txt", "w") as f:
    f.write("Welcome to\n")
    f.write("my website\n")
    f.write("www.csiplearninghub.com")

In the above program we have not called the close() function, the file will automatically closed.

Text File Handling in Python Handout – Part 3

Appending to File

When we want to add more data into a file which already contains some data then we use this append mode. When we open the file in append mode then the following thing happens

  1. It opens the file with file pointer at the end of the file.
  2. If the file does not exist then this mode create a new blank file with pointer in the beginning.

NOTE: In simple words we can understand that append means adding data to a file without erasing the existing content.

Syntax of opening file in append mode

f = open("data.txt", "a")

The above code will open a file “data.txt” in append mode with ‘f’ as a file handle/object.

Understand the concept of Append

Step 1: Open a file and write something

f = open("data.txt"
f.write("Welcome to my site\n")
f.write("csiplearninghub.com\n")
f.close()

Output of above program

Python file handling Part 2

Step 2 : Open a file to add some more data to the above file.

f = open("data.txt", "a")
f.write("File Handling handout part - 1\n")
f.write("File Handling handout part - 2\n")
f.close()

Output of above program

NOTE : In above code when we open file in append mode, it did not erase the existing content and , moreover, added the new content at the end of file.

Text File Handling in Python Handout (Question Answer Session.)

Q1. What do you mean by append mode?
Ans. Append mode is to add new content to a file without erasing the 

Q2. Both append and write mode create a new file, if file does not exist.(T/F)
Ans. True

Q3. Write a program to append the following lines in file "data.txt"
    "Subscribe to my site"
    "Text File Handling in python Handout"
    "Text File Handling in python Handout is a complete tutorial"
Ans. 
f = open("data.txt" , "a")
f.write("Subscribe to my site\n")
f.write(""Text File Handling in python Handout\n")
f.write(""Text File Handling in python Handout is a complete tutorial\n")
f.close()

Q4. What is the difference between a and a+ mode?
Ans. 'a is 'append mode which means we can add new content to a file without erasing the existing
 content while 'a+' is append as well as read mode, means we can write new content as well as read 
  content from file.

Q5. Write a program to write the following data in a file "rollno.txt" in the same format as shown
       below.
                   Roll No.                      Name
                   1                                 Amit
                   2                                 Sumit
                   3                                 Naina

Answer 5.

Python File Handling Handout

Text File Handling in Python Handout (Question Answer Session.)

Q1. Write a program to write the following text in file named "textfile.txt"

                           Welcome to Text File Handling in python Handout
                           Text file handling  in python handout is a complete tutorial
                           I love text file handling in python handout
                           How do you like text file handling in python handout
Ans. 
f = open("textfile.txt", "w")
f.write("Welcome to Text File Handling in python Handout\n")
f.write("Text File Handling in python Handout is a complete tutorial\n")
f.write("I love text File Handling in python Handout\n")
f.write("How do you like text file handling in python handout")
f.close()

Q2. Write a program to read the above created file and display the content.
Ans. Do it yourself

Q3. Write a program to display the following in the file "textfile.txt" (created above)
        1. Number of Vowels
        2. Number of Words
        3. Number of Spaces
        4. Frequency of alphabet 'a'
        5. Frequency of word "Text"
Ans. Do it your self

Related Post

10 Important Questions of Binary File Handling in Python

10 Important Questions of Text File Handling in Python

40+ Important Python File Handling Practice Questions

Handout of Binary File Handling in Python

Class 12 Computer Science Sample Paper 2020-2021.

Class 12 Computer Science Sample Paper Marking Scheme

Class 12 Computer Science Test Series


Share with others

Leave a Reply

error: Content is protected !!