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?
|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?
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.
- 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.
File = open(filename [, mode] [, buffering])
- 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+’
- 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:
|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.
|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?
- 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
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
Q.9 Observe the following code and answer the question that follow:
____________# Blank 1
- What type (Text/Binary) of file is Mydata?
- Fill the Blank 1 with statement to write ”ABC” in the file ”Mydata”.
Q.10 What are the differentiate File Attributes in Python?
- 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?
- 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.
f1.write (“Welcome! Please have a seat”)
Q.14 Differentiate between ‘w’ and ‘a’ modes
“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().
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().
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
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?
- 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.
- 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”.
for i in line:
if (i.isupper() == True):
print("Total no. of upper-case alphabets :",upper)
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.
for a in rec:
if (a.isdigit() != True):
Q.23 Write a program to count the words “to” and “the” present in a text file “python.txt”.
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)
Q. 24 Write a program to display all the lines in a file “python.txt” along with line/record number.
for a in lines:
Q. 25 Write a program to display all the lines in a file “python.txt” which have the word “to” in it.
for a in lines:
if (a.tolower().count(“to”) > 0) :