Reading Text Files
Reading Writing text files
Writing text Files
There are two ways to write in a file.
write() : Inserts the string s in a single line in the text file.
f.write(s)
writelines() : For a list of string elements, each string is inserted in the text file.Used to insert multiple strings at a single time.
L = [str1, str2, str3]
f.write(l)
• write() - for writing a single string
• writeline() - for writing a sequence of strings
Reading from a file
There are three ways to read data from a text file.
read() : Returns the read n bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.
f.read(n)
readline() : Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.
f.readline(n) # read n characters from line
f.readline() # read entire line
readlines() : return list of strings. Reads all the lines and return them as each line a string element in a list.
f.readlines()
Count words in a file
f=open('abc.txt')
c=0
s=f.read() # read file and store the content of file in a string s
w=s.split() # split the contents of s and store it into list w
for i in w:
c=c+1
print(c)
f.close()
Count ‘india’ word from file
f=open('abc.txt')
c=0
s=f.read()
w=s.split()
for i in w:
if(i=="india"):
c=c+1
print(c)
f.close()
Count and print words having length <=3 from file
f=open('abc.txt')
c=0
s=f.read()
w=s.split()
for i in w:
if(len(i)<=3): #match the length of item in list
print(i)
c=c+1
print(c)
Count lines in a file
f=open('abc.txt')
c=0
list=f.readlines() # Read lines from file and store in a list named list
for i in list:
c=c+1
print(c)
f.close()
Q Write a function countmy( )in Python to read the text file “Story.txt” and count the number of times “my” or “My” occurs in the file. For example if the file “Story.TXT” contains:
“This is my website. I have displayed my preferences in the CHOICE section.”
The countmy( ) function should display the output as: “my occurs 2 times”.
def countmy():
f=open('story.txt','r')
c=0
s=f.read()
w=s.split()
for i in w:
if(i=="my or My"):
c=c+1
print("my or My occurs",c,"times")
f.close()
countmy()
Count lines starts from ‘s’
f=open('abc.txt')
c=0
list=f.readlines()
for i in list:
if(i[0]=='s'): # match each item of list starts with s or not
c=c+1
print(c)
f.close()
Count characters from file
f=open('abc.txt')
count=0
s=f.read()
w=s.split()
for i in w: # traverse every item in list
for c in i: # traverse every character in item
count=count+1
print(count)
Count lower case alphabets from file
f=open('abc.txt')
count=0
s=f.read()
w=s.split()
for i in w:
for c in i:
if(i.islower()): # find the given character is lower case or not
count=count+1
print(count)
Count number of digits present in text file
f=open('abc.txt')
count=0
s=f.read()
w=s.split()
for i in w:
for c in i:
if(i.isdigit()): # find the given character is digit or not
count=count+1
print(count)
Print first and last line of text file
f=open('abc.txt')
lines=f.readlines()
print(lines[-1]) # -1 is the index of last item in a list
print(lines[0]) # 0 in the index of first item in a list
Print longest line from a text file
f=open('abc.txt')
c=0
list=f.readlines()
longest=""
for i in list:
if(len(i)>len(longest)):
longest=i
print(longest)
Program to display size of a file in bytes
f=open('abc.txt')
s=f.read() # read file and store the content of file in a string s
size=len(s)
print("size in bytes:",size)
f.close()
Write a program to read a text file and display the count of vowels and consonants in the file
QWrite a user-defined function named count() that will read the contents of text file named “Story.txt” and count the number of lines which starts with either “I‟ or “M‟. E.g. In the following paragraph, there are 2 lines starting with “I‟ or “M‟:
“India is the fastest growing economy.
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.”
Q. Write a function in python to count the number of Uppercase alphabets present in a text file “Story.txt”
def Upperdisplay():
f=open('abc.txt')
count=0
s=f.read()
w=s.split()
for i in w:
for c in i:
if(i.isupper()): # find the given character is lower case or not
count=count+1
print(count)
Q. Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT, and display those words, which are less than 5 characters.
def DISPLAYWORDS():
f=open('abc.txt')
c=0
s=f.read()
w=s.split()
for i in w:
if(len(i)<5): #match the length of item in list
print(i)
Q. Write a user defined function in Python that displays the number of lines starting with ‘H’ in the file story.txt. Eg: if the file contains:
Whose woods these are I think I know.
His house is in the village though;
He will not see me stopping here
To watch his woods fill up with snow.
Then the line count should be 2
Q. Write a user defined function countwords() in python to count how many words are present in a text file named “story.txt”. For example, if the file story.txt contains following text:
Co-education system is necessary for a balanced society. With co-education system, Girls and Boys may develop a feeling of mutual respect towards each other.
The function should display the following:
Total number of words present in the text file are: 24
def countwords() :
f=open('story.txt')
c=0
s=f.read()
w=s.split()
for i in w:
c=c+1
print(" Total number of words present in the text file are:", c)
f.close()
countwords()
OR
def countwords() :
f=open('story.txt')
c=0
s=f.read()
w=s.split()
print(" Total number of words present in the text file are:", len(w))
f.close()
Writing lines , words and characters from one text
file to another file
1. Reading lines from one file and write into another file starting from 's'
r=open('read.txt',"r") # open file in read mode
w=open("write.txt",'w') # open file in write mode
lines=r.readlines()
for line in lines:
if(line[0]=='s'): # write all lines start from 's' from read.txt to write.txt
w.write(line)
r.close()
w.close()
2. Write first and last line of one file into another file
r=open('read.txt',"r") # open file in read mode
w=open("write.txt",'w') # open file in write mode
lines=r.readlines()
w.write(lines[0]) # write first line
w.write(lines[-1]) # write last line
r.close()
w.close()
3. Write lines of one file into anther in reverse form
r=open('read.txt',"r")
w=open("write.txt",'w')
lines=r.readlines()
for line in lines:
w.write(line[::-1]) # write line in reverse form
r.close()
w.close()
contents of read.txt
my name is mukesh
pgt computer Science
Contents of write.txt file
hsekum si eman ym
ecneicS retupmoc tgp
4. Write only digits from one file to another
fr=open('read.txt',"r")
fw=open("write.txt",'w')
s=fr.read()
w=s.split()
for i in w:
for c in i:
if c.isdigit(): # check character for digit
fw.write(c)
fr.close()
fw.close()
Contents in read.txt
pin code 160014
Mobile no 9646648307
E=mail id: mk168in@gmail.com
Contents in write.txt file
1600149646648307168
5.Writing upper,lower case characters and other characters input by keyboard in different files
f1=open('lower.txt',"w")
f2=open('upper.txt',"w")
f3=open('other.txt',"w")
n=int(input("How many characters you want to enter "))
for i in range(n):
ch=input("Enter a character")
if ch.islower():
f1.write(ch)
elif ch.isupper():
f2.write(ch)
else:
f3.write(ch)
f1.close()
f2.close()
f3.close()
Appending data in text 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. The definition of these access modes are as follows:
Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
Append and Read (‘a+’): Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
When the file is opened in append mode, the handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
# Python program to illustrate
# Append vs write mode
f1 = open("abc.txt", "w")
L = ["This is Arawali \n", "This is Udaigiri \n", "This is Shivalik"]
f1.writelines(L)
f1.close()
# Append-adds at last
f1 = open("abc.txt", "a") # append mode # contents added at end
f1.write("Today \n")
f1.close()
f1 = open("abc.txt", "r")
print("Output of Readlines after appending")
print(f1.read())
print()
f1.close()
# Write-Overwrites
f1 = open("abc.txt", "w") # write mode # contents are overrite
f1.write("Tomorrow \n")
f1.close()
f1 = open("abc.txt", "r")
print("Output of Readlines after writing")
print(f1.read())
print()
f1.close()
output
Output of Readlines after appending
This is Arawali
This is Udaigiri
This is ShivalikToday
Output of Readlines after writing
Tomorrow
Append data from new line
In the above example, it can be seen that the data is not appended from the new line. This can be done by writing the newline '\n' character to the file.
add code as
# writing newline character
file1.write("\n")
file1.write("Today")
Now output will be
Output of Readlines after appending
This is Arawali
This is Udaigiri
This is Shivalik
Today
Access modes in Text File
It govern the type of operations possible in the opened file. It refers to how the file will be used once its opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. There are 6 access modes in python.
Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exists, raises I/O error. This is also the default mode in which file is opened.
Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exists.
Write Only (‘w’) : Open the file for writing. For existing file, the data is truncated and over-written. The handle is positioned at the beginning of the file. Creates the file if the file does not exists.
Write and Read (‘w+’) : Open the file for reading and writing. For existing file, data is truncated and over-written. The handle is positioned at the beginning of the file.
Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
Standard Streams: Stdin, Stdout, Stderr:
Standard Streams:
stdin: Standard Input Device (Ex. Reading from Keyboa
Stdout: Standard Output Device (Ex. Printing on Monitor)
Stderr: Same as stdout but normally only for errors.
Internally these standard devices are implemented as files called
Standard Streams. These are available in sys Module.
After importing sys Module we can use these Standard Streams in
the same way you use other files.
sys.stdin.read() – let you read from keyboard
sys.stdout.write() – let you write of the standard output Device
sys.stderr.write() – let you write the error
When we start python these files opened in:
stdin(read mode)
stout(write mode)
stderr(write mode)
Example 1
contents of abc.txt is print(write) on output device (monitor or screen)
import sys
f=open("abc.txt")
line1=f.readline()
line2=f.readline()
sys.stdout.write(line1)
sys.stdout.write(line2)
f.close()
Example-2
import sys
a=sys.stdin.read(3) # read from input device
sys.stdout.write(a) # write at output device
b=sys.stdin.read(5)
sys.stdout.write(b)
sys.stderr.write("Custom error message") # write error message
Absolute Vs Relative Path
Absolute Path – It is a full path of the file from the root directory.
Ex : - C:\Users\Tanmay\Desktop\Delete\file handling.txt
Relative Path – It is the path of the file from the current working directory.
Ex: -
If I am on Desktop then the relative Path for file “file handling.txt” is .\Delete\file handling.txt
Reading text file using relative path if python file and txt file both in same folder
f=open('abc.txt')
s=f.read() # read file and store the content of file in a string s
w=s.split() # split the contents of s and store it into list w
print(w)
f.close()
Reading text file using absolute path if python file and txt file both are in different folder or location in Drive
suppose text file abc.txt placed in demo folder of D drive in computer
#f=open('readme.txt') not working give error file not exist
f=open("D:/demo/readme.txt")
s=f.read() # read file and store the content of file in a string s
w=s.split() # split the contents of s and store it into list w
print(w)
f.close()
Every file has its own identity associated with it. Which is known as –
a. icon b. extension c. format d. file type
Which of the following is not a known file type?
a. .pdf b. jpg c. mp3 d. txp
In f=open(“data.txt”, “r”), r refers to .
a. File handle b. File object c. File Mode d Buffer
EOL stands for
a. End Of Line b. End Of List c. End of Lines d. End Of Location
Which of the following file types allows to store large data files in the computer memory?
a. Text Files b. Binary Files c. CSV Files d. None of these
Which of the following file types can be opened with notepad as well as ms excel?
a. Text Files b. Binary Files c. CSV Files d. None of these
Which of the following is nor a proper file access mode?
a. close b. read c. write d. append
In F=open("MyFile.txt") , name of file object is
a.open b.MyFile.txt c.F d.F=open()
Default EOL character in Python.
a. ‘\n’ b. ‘\r’ c. ‘’ d. ‘\t’
Which of the following is not a file extension for text files?
a. .txt b. .ini c. .rtf d. .DAT
What is the first thing to do before performing any functions on a text file?
a. Import modules b. Open file
c. Read file d. Print the name of the file
What is a file object?
a. It serves as a link to the file.
b. It is a file present in a computer.
c. A keyword
d. A module in python
Which is not a correct file mode for text files?
a. a b. ar c. a+ d. r+
What does the prefix r in front of a string do?
a. It makes the string a raw string b. It opens the file in read mode
c. It converts the file into text file d. It creates the file if it doesn’t exist
A file object is also known as
a. File handle b. File copy c. File directory d. File link
How to open a text file in read mode only?
a. r b. r+ c. rb+ d. rw+
How to open a text file in write and read mode?
a. r+ b. a+ c. wr d. wb
Syntax for closing a file:
a. closefile(<file object>)
b. <fileobject>.close()
c. <filename>.closer()
d. closefile.<fileobject>
Which method can not be used to read from files?
a. read() b. readlines()
c. readlines(<filename>) d. readline()
What does strip() function do?
a. Removes the trailing or leading spaces, if any.
b. Deletes the file
c. Remove the file object
d. Removes all the spaces between words
readlines() gives the output as
a. List b. Tuple c. String d. Sets
When reading a file using the file object, what method is best for reading the entire file into a single string?
a. readline() b. read_file_to_str()
c. read() d. readlines()
Which file can open in any text editor and is in human readable form?
a. Binary files b. Text files c. Data files d. Video files
Which function breaks the link of file-object and the file on the disk?
a. close( ) b. open( ) c. tell( ) d. readline( )
Which function reads the leading and trailing spaces along with trailing newline character ('\n') also while reading the line?
a. readlines( ) b. readline( ) c. read( ) d. flush( )
Which mode is used to retain its previous data and allowing to add new data?
a. write mode b. read mode c. open mode d. append mode
Which function forces the writing of data on disc still pending in output buffer?
a. seek( ) b. tell( ) c. flush( ) d. write( )
Syntax for flush( ) function is:
a. <fileOobject>(flush( ))
b. flush( ).<fileobject>
c. <fileObject>.flush( )
d. flush( ).<file-object>
Which function returns the entire file content in a list where each line is one item of the list?
a. readlines( ) b. readline( ) c. output( ) d. Input( )
Which function is used to remove the given character from trailing end i.e. right end?
a. strip( ) b. remove( ) c. Istrip( ) d. rstrip( )
Sometimes the last lap of data remains in buffer and is not pushed onto disk until a operation is performed.
a. dump( ) b. close( ) c. load( ) d. open( )
The position of a file-pointer is governed by the .
a. File mode b. append mode
c. write mode d. open mode
In which mode the file must exist already, otherwise python raises an error?
a. read mode b. write mode c. binary mode d. None of these
What is the prefix r stands for in file path?
a. raw string b. read c. write d. append
In which mode if the file does not exist, then the file is created?
a. read write mode b. read mode c. write mode d. All of these
Which option is correct about this program?
f=open(“ss.txt”,”wb”)
print(“Name of the file:”,f.name)
f.flush()
f.close()
a. Compilation error b. Runtime error
c. No output d. Flushes the file when closing them
What is the output of the following?
import sys
sys.stdout.write(‘Hello\n’)
sys.stdout.write(‘Python\n’)
a. error b. Runtime error c. Hello Python
d. Hello
Python
Which function is used to read all the characters in text files?
a. read( )
b. readcharacters( )
c. readall( )
d. readchar( )
Which function is used to read all the lines?
a. read( ) b. readall( )
c. readlines( ) d. readline( )
In which format does the readlines( ) function give the output?
a. Integer type b. list type
c. string type d. tuple type
In which format does the read( ) function give the output?
a. Integer type b. string type
c. list type d. tuple type
Which function is used to write a list of strings in a file?
a. writestatement() b. writelines()
c. writefulline() d. writeline()
Which function is used to write all the characters?
a. writechar() b. writecharacters()
c. write() d. writeall()
What is the correct syntax of open() function?
a. file=open(file_name[,access_mode][,buffering])
b. fileobject=open(file_name[,access_model][,buffering])
c. fileobject=filename.open()
d. none of the mentioned
In file handling, what does means “r”, “a”?
a. append, read b. read, append
c. read, add d. None of the mentioned
The default file open mode is….
a. w b. r+ c. w+ d. r
What is the difference between r+ and w+ modes?
a. In r+ mode, file length truncates to zero.
b. In w+ mode, file length truncates to zero either file exists or not.
c. No difference
d. Depends on the operating system
A file maintains a which tells the current position in the file where writing or reading will take place.
a. line b. file pointer c. list d. order
Which of the following statements is true regarding the opening modes of a file?
a. While opening a file for reading, if the file does not exist, an error occurs.
b. While opening a file for writing ,if the file does not exist, an error occurs.
c. While opening a file for reading, if the file does not exist, a new file is created. d. None of the above.
To force python to write the contents of file buffer on to storage file,........method may be used.
a. buffer() b. flush() c. close() d.write()
Which of the following statements are true?
a) When you open a file for reading, if the file does not exist, an error occurs.
b) When you open a file for writing, if the file does not exist, a new file is created.
c) When you open a file for writing, if the file exists, the existing file content is overwritten with the new content.
d) All of the these
To read the next line of the file from a file object f1, we use:
a) f1.read(2) b) f1.read() c) f1.readline() d)f1.readlines()
Write a function ETCount() in Python, which should read each character of a text file “TESTFILE.TXT” and then count and display the count of occurrence of alphabets E and T individually (including small cases e and t too).
Example:
If the file content is as follows:
Today is a pleasant day.
It might rain today.
It is mentioned on weather sites
The ETCount() function should display the output as: E or e: 6 T or t : 9
def ETCount() :
Write a method COUNTLINES() in Python to read lines from text file ‘TESTFILE.TXT’ and display the lines which are not starting with any vowel.
Example:
If the file content is as follows:
An apple a day keeps the doctor away.
We all pray for everyone’s safety.
A marked difference will come in our country.
The COUNTLINES() function should display the output as:
The number of lines not starting with any vowel - 1