100% found this document useful (2 votes)
8K views11 pages

Class 12 Python Text File Handling Guide

The document discusses working with text files in Python. It explains that text files store text as a sequence of bytes represented by 0s and 1s, and text editors translate these bytes into readable characters. It then covers opening a file using open(), reading a file's contents using read(), readline(), and readlines(), and closing a file. The different modes for opening a file like read, write, append are explained. It also discusses writing to a file using write() and writelines() functions. Various examples are provided to demonstrate reading, writing, counting words and lines in a text file.

Uploaded by

Ayush Prasad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
8K views11 pages

Class 12 Python Text File Handling Guide

The document discusses working with text files in Python. It explains that text files store text as a sequence of bytes represented by 0s and 1s, and text editors translate these bytes into readable characters. It then covers opening a file using open(), reading a file's contents using read(), readline(), and readlines(), and closing a file. The different modes for opening a file like read, write, append are explained. It also discusses writing to a file using write() and writelines() functions. Various examples are provided to demonstrate reading, writing, counting words and lines in a text file.

Uploaded by

Ayush Prasad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

LANCER’S CONVENT- 2021-2022

STUDY MATERIAL CLASS XII


DATA FILE HANDLING

Text Files:
A text file can be understood as a sequence of characters consisting of alphabets, numbers and other special
symbols. Files with extensions like .txt, .py, .csv, etc. are some examples of text files. When we open a text
file using a text editor (e.g., Notepad), we see several lines of text. However, the file contents are not stored
in such a way internally. Rather, they are stored in sequence of bytes consisting of 0s and 1s.
The text editor translates each ASCII value and shows us the equivalent character that is readable by the
human being.
For example, the ASCII value 65 (binary equivalent 1000001) will be displayed by a text editor as the letter
‘A’ since the number 65 in ASCII character set represents ‘A’.

Each line of a text file is terminated by a special character, called the End of Line (EOL). For example, the
default EOL character in Python is the newline (\n).

In these Notes, We’ll learn how to


1) Open a Text file,
2) Read its contents
3) Close a file

Using python programming

Working with text files in a Python program

OpenàProcessàClose
To open a file in Python, we use the open() function. The syntax of open() is as follows:
file_object= open(file_name, access_mode)

This function returns a file object also called file handle which is stored in the variable
file_object. We can use this file_object to transfer data to and from the file (read and write)

fh= open(“hello.txt”, ‘r’)


r is the mode in which file is opened
Here, fh is file handle/file object.
hello.txt is the name of text file that you want to open
‘r’ is the mode which means that the file is opened for reading (not writing)

If you do not specify the mode and open the file using the statement given below, then the file will be
automatically opened in reading mode.

fh= open(“hello.txt”) # we did not specify the mode ‘r’ explicitly

The file_object has certain attributes that tells us basic information about the file, such as:
1) file_object.closed: returns true if the file is closed and false otherwise
2) file_object.mode: returns the access mode in which the file was opened.
3) file_object.name: returns the name of the file.
Absolute and relative Path

file_object= open(file_name, access_mode)
The file_name should be the name of the file that has to be opened.
If the file is present in current working directory, then only name of the file is required(relative path)
If the file is not in the current working directory, then we need to specify the complete path of the file along with its
name (absolute path)

Example: relative path


File1=open(“newfile.txt”, ‘r’)

Example: absolute path (two back slash required)

File2=open(“C:\\Users\\Desktop\\noname\\hello.txt”)

Example: absolute path with prefix ‘r’ (raw string, only one back slash required)

File3=open(r“C:\Users\Desktop\noname\hello.txt”)

Closing the file

Once we are done with the read/write operations on a file, it is a good practice to close the file.
Python provides a close() method to do so. While closing a file, the system frees the memory
allocated to it. The syntax of close() is:
file_object.close()
Here, file_object is the object that was returned while opening the file.
Python makes sure that any unwritten or unsaved data is flushed off (written) to the file before it is closed.

Various modes to open a file


'r' : Read mode only. It will open the file only if already exists on the disk.(FileNotFoundError Otherwise)
File offset position: Beginning of the file

‘w’: Write Mode. File will be truncated on opening. If file does not exist, a new file is created.
File offset position: Beginning of the file

r+ : Read as well as write. File will be opened only if it exists on the disk. (Contents are not deleted on opening
the file) File offset position: Beginning of the file

'w+' : Write as well as read: It will open the file but previous data will truncated. If file does not exist on the
disk, a new file is created. File offset position: Beginning of the file

'a' : Append Mode: It will open the file for writing. Previous data is not deleted on opening the file. It will add
the data at the end of file. A new file is created in case file does not exist. File offset position: End of the file

'a+': Write and Read: It will open the file for writing and reading. Previous data is not deleted on opening the
file. It will add the data at the end of file. File offset position: End of the file
READING FROM A TEXT FILE
In order to read the contents of a file, we first need to open a file and create it’s handle.
Then we may use any of the following functions for reading the file
1) read() 2) readline() 3) readlines()

1) read(): It reads the entire contents of the file and returns a STRING (string containing whole file
contents). In case you specify no of bytes aswell, it will read only n bytes. [i.e. using read(n)]

fh.close()

OUTPUT

Q. Read and print first 9 characters from file hello.txt (contents of this file shown above)

fh.close()

OUTPUT:

Q. There is a file called CS.txt. Its contents are shown below. Find output of code below:
\

fh.close()
CS.txt

Ans: (count space also as one character)

2) readline(): This function reads one line at a time as a STRING. A line terminates with
‘\n’). The new line character is also read from the file and post-fixed in the string.

(readline(n): It can also be used to read a specified n of bytes of data from a file but maximum up
to the newline character (‘\n’) )

Q3. Read first line two lines from the file CS.TXT (shown above) and display first two
lines.

fh.close()

OUTPUT:

Q4. Read all the lines one by one from the file Notes.TXT (contents shown below) and
display them(without displaying extra newline between the lines)

Notes.txt
Ans:

OUTPUT:

3) readlines():

The method reads all the lines and returns the lines along with newline(\n) as a list of strings. The following
example uses readlines() to read data from the text file myfile.txt containing 3 lines.

Example1:
>>> myobject=open("myfile.txt", 'r')
>>> print(myobject.readlines())
['Hello everyone\n', 'Writing multiline strings\n', 'This is the third line']
>>> myobject.close()

Important: Pls note that each line (not each word) becomes a list element when we use
readlines()

Q. WAP to count the number the lines in a file.

f1=open(‘abcd.txt’, "r")
x=f1.readlines() # read whole file in form of a list
print (len(x))
f1.close()

Q. Write a program to find the size of a file.

f1=open("xyz.txt", "r")
x=f1.read() # read whole file in a string x
print (len(x)) #it will count the spaces, \n and all other special characters
f1.close()

Q. Write a program to count words in a file named fewwords.txt as shown


below:

We are writing a few words here.


Our program will return the
number of words in this file.
f1=open(“Fewwords.txt", "r")
s1= f1.read() # read whole file
list1= s1.split() #it will split the words on the basis of whitespaces
print (list1)
print ("No of words: ",len(list1))
f1.close()

OUTPUT:

['We', 'are', 'writing', 'a', 'few', 'words', 'here.', 'Our', 'program',


'will', 'return', 'the', 'number', 'of', 'words', 'in', 'this', 'file.']

No of words: 18

Q. WAP to find the total occurrences of the word ‘are’ in a given file
abc.txt.
abc.txt
We are 100 people. We all are friends. Some
are students.
We are going to picnic tomorrow

Ans:

f1=open(“abc”.txt", "r")
s1= f1.read() #read whole file
list1=s1.split() #List1 will contain the words
count=0
for element in list1:
if element=="are":
count+=1
print ("no of occurrences: ", count)
f1.close()

OUTPUT:
no of occurrences: 4
Q. Read a file STORY.TXT and Store the words starting with a vowel in
another file named “second.txt”.

fh1= open("story.txt", 'r')


fh2= open("second.txt", 'w') # open the file in write mode
str1=fh1.read() # read whole file
lst= str1.split() # split the string into words
count=0
for word in lst: # move character by character
if word[0] in "aeiouAEIOU": #if character is a vowel
fh2.write(word+"\n")

fh1.close()
fh2.close()

Q. Write a program to count the number of spaces (blank characters) in


atext file named “STORY.TXT”.

fh= open("para.txt")
str1=fh.read() # read whole file
count=0
for ch in str1: # move character by character
if ch==' ': #if ch is a space
count+=1
print(count)
fh.close()

Q. Write a program to read the content from a text file STORY.TXT, count
and display the number of alphabets present in it.

fh1= open("para.txt", 'r')

str1=fh1.read()
count=0
for ch in str1:
if ch.isalpha()==True:
count+=1
print (count)
fh1.close()
WRITING IN A TEXT FILE
After working with file-reading functions, let's talk about the writing in to text file. We will discuss two
functions :
• write()
• writelines()

1) The write() function writes a string on to a file.


Note: If you want to write multiple lines one after the another in a file using write() function, don't
forget to add "\n" at the end of each line so that a new line starts in next line.

Following program will explain this:

fout=open("student.txt", "w")
for i in range (5): # it will run 0 to 4
name=input("enter the name of the student: ")
fout.write(name)
fout.close()

RiyaRehanRonaqRanveerSahil

student.txt

The reason that all the names are being displayed in the single line in file student.txt is that we didnot write
a "\n" after writing each name in the file. The above program can be modified as shown below:

fout=open("student.txt", "w")
for i in range (5): # it will run 0 to 4
name=input("enter the name of the student: ")
fout.write(name+'\n') # join new line character
fout.close()

output
2) writelines(): This function is used to write a list onto a file.(write() function writes a string whereas
writelines() writes a list onto the file).

Following program will explain its working:

fileout=open("student.txt", "w")
list1=[]
for i in range (5):
name=input("enter the name of the student: ")
list1.append(name+"\n") #keep on writing all the names in the list

print(list1)
fileout.writelines(list1) #write the contents of the list on to the file.
fileout.close()


OUTPUT:

student.txt

Q WAP to write three records on to a file name student in the following format:
12,hazel,98.75
15,nidhi,97.75
16,meera,100

Soln:
fileout=open("student.txt", "w")
for i in range (3):
rollno=input("enter the rollno of the student: ")
name=input("enter the name of the student: ")
marks= input("enter the marks of the student: ")
record=rollno+","+name+","+marks+"\n"
fileout.write(record)
fileout.close()

OUTPUT:
Q WAP to add two more records to the file that has been created in the program above (append
mode)

fileout=open("student.txt", "a") #note that it is opened in append mode


for i in range (2): # it will run 0 to 1
rollno=input("enter the rollno of the student: ")
name=input("enter the name of the student: ")
marks= input("enter the marks of the student: ")
record=rollno+","+name+","+marks+"\n"
fileout.write(record)

fileout.close()

Flush() Function
When you write on to a file using any of the write functions, Pythons holds everything in buffer and pushes it into actual
file a later time. If, however you want python to force write the contents of the buffer on to the file, you can use flush()
function.

Python automatically flushes from buffer to file when we use close() function. But we can use flush() when we want to
use it.
Syntax:

fileobject.flush()

Removing whitespace after reading from the file


Consider the text file given below

Let’s write a function to read and display the contents of this file by using the readline() function

Program:
Output:

We can observe that there is extra line gap between the lines, this is because readline() reads a full line. A line is
considered till a newline character( EOL) is encountered in the data file.
In order to remove this we can use rstrip(‘\n’) to remove the newline character from the end of the line.

Output:

We can also use the following methods to remove whitespaces as learned in STRINGS datatype (Check string
functions studied in Class XI)

strip()
rstrip()
lstrip()

SEEK & TELL FUNCTIONS


The positioning of cursor in the file
• Functions:
o tell
o seek

The tell() function:


- The meaning of tell is to say something.
- Similarly tell function() say/tell us about the current position of the cursor in file.
Ex. f = open(“intro.txt”,”r”)
print(f.tell())

The seek() function:


- It moves the cursor at required position in the file.
- Where offset is the position where you want to move your file From is the place from which place you want to
move
Ex. f.seek(5,0) which means moves a cursor to 5th character from the begginig

You might also like