Questions on Text File Handling in Python
- Categories Python File Handling, Python
In this post we will cover Text File Handling in Python. You can watch our video on Text File Handling in Python – Click Here.
Q.1 Differentiate between Text file and Binary files?
Ans.
Text Files | Binary Files |
---|---|
Stores in ASCII or Unicode format so human readable | Contains raw data so not human readable |
Each line is delimited by EOL or end of Line (\n). | No delimiter for a line |
Usually with extension .txt and can be opened in notepad | Has app specific extension and needs specific app to open like word, excel, jpg etc. |
Slower than Binary File | Faster than text files |
Q. 2 What are the different operations we can perform on file?
Ans.
There are three basic operations we can perform on file
- Read – r mode
- Write – w mode
- Append – a mode
Q. 3 How to open and close file? Also give the Syntax for same.
Ans.
- The key function for working with files in Python is the open() function.
- The open() function takes two parameters; filename, and mode and it returns a File Handle.
- Syntax:
File = open(filename [, mode] [, buffering])
File.close()
- Where, filename is name of the file we want to access
- mode is a string like
- “r” for reading
- “w” for writing
- ‘a’ for append
- “ab’, ‘a+’, ‘ab+’
- buffering
- 0 Means no buffering
- 1 Yes to buffering
- > 1 considered buffer size
Q. 4 What are different modes to open a file?
Ans. Mode for a file:
Mode | Description |
---|---|
t | Open in Text Mode (default option) |
b | Open in Binary Mode |
r | Open in read mode (Default Option) – Gives error if file does not exist |
w | Open in Write mode – Overwrite file if it exist – Create File if it does not exist |
a | Open in Append mode – Append at end if exists – Create new file if it does not exist |
r+ | Open for reading and writing – File MUST exist – Does not truncate the file |
w+ | Open for writing + reading -Creates new file if it does not exist – Truncates the file if it exists |
x | Open for exclusive creation |
Q. 5 Differentiate between file modes r+ and w+ with respect to Python.
Ans.
r+ | w+ |
File must exist otherwise error is raised | File is created if it does not exist. If exists, the data is truncated |
Cannot truncate a file | Can truncate a file if it exists |
Q.6 What is file handle?
Ans.
- When we call the open command, it returns to us a file object or reference to the file, it is called file handle.
- This file handle is used to carry out any subsequent operation on the file like read or write.
Q.7 Write a statement in Python to perform the following operations
- To open a text file “MYPET.TXT” in write mode
- To open a text file“MYPET.TXT” in read mode
Ans. f1=open(“MYPET.TXT”,’w’)
f2=open(“MYPET.TXT”,’r’)
Q.8 Write a statement in Python to perform the following operations
- To open a binary file “LOG.DAT” in read mode
- To open a binary file“LOG.DAT” in write mode
Ans.
- Fileobj=open(“LOG.DAT”,’rb’)
- Fileobj=open(“LOG.DAT”,’wb’)
Q.9 Observe the following code and answer the question that follow:
File=open(“Mydata”,”a”)
____________# Blank 1
File.close()
- What type (Text/Binary) of file is Mydata?
- Fill the Blank 1 with statement to write ”ABC” in the file ”Mydata”.
Ans.
Text file
File.write(“ABC”)
Q.10 What are the differentiate File Attributes in Python?
Ans.
- closed: Returns true if file is closed, false otherwise.
- mode: Returns access mode with which file was opened.
- name: Returns name of the file.
- softspace: Returns false if space explicitly required with print, true otherwise.
Q.11 How do you find no of characters, now of words or number of lines in Python text file?
Ans.
- Size of file in bytes = len(file.read())
- Number of words = len(file.read().split())
- Number of lines = len(file.readlines())
Q.12 What is file mode? Name the default file mode.
Ans. A file mode governs the type of operations possible in the opened file. The default mode is read(‘r’)
Q.13 Write a statement to write the string”Welcome! Please have a seat” in the file wel.txt, that has not yet been created.
Ans.
f1=open(“wel.txt”,’w’)
f1.write (“Welcome! Please have a seat”)
Q.14 Differentiate between ‘w’ and ‘a’ modes
Ans. “w” write mode “a” append mode File overwrites an existing file or creates a non-existing file File retains the old data and adds new data to the file Opens a file for writing and reading Opens a file for both appending and reading
Q.15 How is r+ file mode different from rb+ mode?
Ans. r+ is used to read or write a normal Ascii or Unicode file whereas rb+ mode is used to read or write a binary file
Q. 16 Differentiate between read() and readlines().
Ans.read() readlines() This function is used to read the file together in one string This function is used to read all lines from the file and return a list with each line as separate string. It returns string It returns list of Strings. e.g. F1.read() e.g. F1.readLines()
Q.17 Differentiate write() and writelines().
Ans.write() writelines() write() function writes a string into the file writelines() function takes in a List of strings and writes that to the file. Syntax= Syntax= Write string str1 to file referenced by Writes all strings in list L as lines to file referenced by
Q.18 Differentiate between Absolute Pathnames and Relative Pathnames
Ans.Absolute Pathnames Relative Pathnames Absolute paths are from the topmost level of the directory structure The relative paths are relative to current working directory denoted as a dot(.) while its parent directory is denoted with two dots(..) Example: open(“C: Files/myfile.txt”, ‘r’) Example: open(“myfile.txt”, ‘r’)
Q.19 What is standard input, output and error steams?
Ans.
- 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.
Q.20 Write a short note on flush() function.
Ans.
- 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.
Q.21 Write a program to count the number of upper-case alphabets present in a text file “PYTHON.TXT”.
Ans.
def uppercount():
upper=0
f1=open("PYTHON.txt",'r')
line=f1.read()
for i in line:
if (i.isupper() == True):
upper+=1
print("Total no. of upper-case alphabets :",upper)
uppercount()
Q. 22 A text file “PYTHON.TXT” contains alphanumeric text. Write a program that reads this text file and writes to another file “PYTHON1.TXT” entire file except the numbers or digits in the file.
Ans.
fh=open(“python.txt","r")
fw=open(“python.txt","w")
rec=fh.read();
for a in rec:
if (a.isdigit() != True):
print(a,end=' ')
fw.write(a)
fh.close()
fw.close()
Q.23 Write a program to count the words “to” and “the” present in a text file “python.txt”.
Ans.
fname = "python.txt"
num_words = 0
f= open(fname, 'r')
words = f.read().split()
for a in words:
if (a.tolower() == “to” or a.tolower() == “the” ):
num_words = num_words + 1
print("Number of words:", num_words)
f.close()
Q. 24 Write a program to display all the lines in a file “python.txt” along with line/record number.
Ans.
fh=open("python.txt","r")
count=0
lines=fh.readlines()
for a in lines:
count=count+1
print(count,a)
fh.close()
Q. 25 Write a program to display all the lines in a file “python.txt” which have the word “to” in it.
Ans.
fh=open("python.txt","r")
count=0
lines=fh.readlines()
for a in lines:
if (a.tolower().count(“to”) > 0) :
print(a)
fh.close()