Professional Documents
Culture Documents
CHAPTER 2 - FILE HANDLING-txtfile
CHAPTER 2 - FILE HANDLING-txtfile
TEXT FILES
I. INTRODUCTION:
• Files are named locations on disk to store related information.
They are used to permanently store data in a non-volatile
memory (e.g. hard disk).
• Since Random Access Memory (RAM) is volatile (which loses
its data when the computer is turned off), we use files for future
use of the data by permanently storing them.
• When we want to read from or write to a file, we need to open
it first. When we are done, it needs to be closed so that the
resources that are tied with the file are freed.
• Hence, in Python, a file operation takes place in the following
order:
– Open a file
– Read or write (perform operation)
– Close the file
II Types of File in Python
There are three types of files in Python and each of them are
explained below in detail with examples for your easy
understanding. They are:
Buffering:
• Buffering is the process of storing a chunk of a file in a
temporary memory until the file loads completely. In python
there are different values can be given. If the buffering is set to
0 , then the buffering is off. The buffering will be set to 1 when
we need to buffer the file.
Examples of Opening TEXT Files in Python
# open file in current directory(Relative path)
f = open("test.txt“, “r”) # Relative path
# specifying full path(absolute path)
f = open(r“D:\temp\data.txt“, “r”) #–raw string
f = open(“D:\\temp\\data.txt“, “r”) #-absolute path
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read())
Output:
Hello World
Hello Python
Good Morning
How are you
Example 3:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline(2))
Output:
He
This function returns the first 2 characters from the first
line.
Example 4:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline())
Output:
Hello World
Using this function, we can read the content of the file on a line-
by-line basis.
Example 5:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readlines())
Output:
[‘Hello World\n’, ‘Hello Python\n’, ‘Good Morning\n’, ‘How are
you\n]
Here, the readlines() method reads all the lines present inside
the text file including the newline characters and returns them
in the form of list.
#In this example, we are trying to read only the 4th line from the
‘test.txt’ file using a “for loop”. When you iterate over a file-
handle using a for loop, then the for loop’s variable moves
through the file line by line where a line of a file is considered
as a sequence up to and including a special character called
the newline character(\n). So the for loop’s variable starts with
the first line and with each iteration, it moves to the next line. As
the for loop iterates through each line of the file, the loop
variable will contain the current line of the file as string of
characters.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World”)
The above code writes the String ‘Hello World’ into the ‘test.txt’
file.
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World\n”)
my_file.write(“Hello Python”)
The above code writes both the string “Hello World” and “Hello
Python” into the file test.txt. We have mentioned “\n” character
after Hello World, so the cursor will be positioned in the next
line. Hello Python will be written in the new line.
Note: If new line character “\n” is not mentioned, then the
output will be printed as “Hello WorldHello Python”.
Example 3:
fruits = [“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”]
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.writelines(fruits)
The above code writes a list of data into the ‘test.txt’ file
simultaneously.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“Strawberry”)
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“\nGuava”)
The above code appends the string ‘Apple’ at the end
of the ‘test.txt’ file in a new line.
flush() function
• When we write any data to file, python hold everything in
buffer (temporary memory) and pushes it onto actual file later. If
you want to force Python to write the content of buffer onto
storage, you can use flush() function.
• Python automatically flushes the files when closing them i.e. it
will be implicitly called by the close(), BUT if you want to flush
before closing any file you can use flush()
File Pointer
• Every file maintains a file pointer which tells the current
position in the file where reading and writing operation will take.
• When we perform any read/write operation two things
happens:
– The operation at the current position of file pointer
– File pointer advances by the specified number of bytes.
seek
The seek() function in Python is used to move the file cursor to
the specified location. When we read a file, the cursor starts
at.the beginning, but we can move it to a specific position by
passing an arbitrary integer (based on the length of the content
in the file) to the seek() function.
We have opened the file in text mode, moved the cursor to the
62nd position, and set the reference point as the file’s current
position. Then we are attempting to open the file.
tell()
The seek() function is used to set the position of the file cursor,
whereas the tell() function returns the position where the cursor
is set to begin reading. The tell() function takes no parameter
# Opening a file
with open('sample.txt', 'r') as file:
# Using tell() function
pos = file.tell()
# Printing the position of the cursor
print(f'File cursor position: {pos}')
# Printing the content
data = file.read()
print(data)
Difference
seek() tell()
Used to set the file cursor to the Used to tell the position of the file
specific position. cursor.
import sys
fh=open(“poem.txt”)
line1=fh.readline()
line2=fh.readline()
sys.stdout.write(line1)
sys.stdout.write(line2)
sys.stderr.write(“No errors occurred”)
1- MARK QUESTIONS
1. To read three characters from a file object f, we use ……… .
(a) f.read(3) (b) f.read() (c) f.readline() (d) f.readlines()
Q1. Write a single loop to display all the contents of a text file
file1.txt after removing leading and trailing WHITESPACES
out=open('output.txt','w')
out.write('hello,world!\n')
out.write('how are you')
out.close( )
open('output.txt').read( )
Q2. Read the code given below and answer the questions
f1=open('main.txt','w')
f1.write('bye')
f1.close()
If the file contains 'GOOD' before execution, what will be the
content of the file after execution of the code?
Ans2
The file would now contain “Bye” only because when an
existing file is opened in write mode. It truncates the existing
data in file.
Ans3
i) Text file
ii) f1.write(“abc”)
Ans4
ab and a+b mode
Ans5
a) string b)string c)string d)list
Ans6
No Output
Explanation: the f1.read() of line 2 will read entire content of file
and place the file pointer at the end of file. for f1.read(5) it will
return nothing as there are no bytes to be read from EOF and,
thus, print statement prints nothing.
Ans 7
Standard input device(stdin) reads from the keyboard
Standard output device(stdout)- prints to the display and can
be redirected as standard input
Standard error device(stderr)- Same as stdout but normally
only for errors. Having error output separately allows the user
to divert regular output to a file and still be able to read error
messages.
Ans 8
While writing, Python writes everything into a buffer and
pushes it into file at a later time.
When flush() function is called it immediately empties the
buffer and writes into the file.
This function is called automatically when file is closed.
3 MARK QUESTIONS
Q1. Write a python code to find the size of the file in bytes,
number of lines and number of words.
Q2. Write code to print just the last line of a text file “data.txt”.
Ans: fin=open(“data.txt”,”r”)
lineList=fin.readlines()
print(“Last line = “, lineList[-1])
Q4. Reuse the same code for counting digits, spaces, vowels,
Specific characters.
Q5. Write a program to count the words “to” and “the” present
in the text file “India.txt”.
file = open("India.txt","r")
words=((file.read()).lower()).split()
count=0
for i in words:
if i=='in' or i=='the':
count+=1
print("Total=", count)
file.close()
Q6. Write a program to find the longest word present in the text
file “input.txt”.
Ans:
file = open("India.txt","r")
words=((file.read()).lower()).split()
largest=" "
for i in words:
if len(largest)<len(i):
largest=i
print("Largest=",largest)
file.close()