File Handling Ques-Ans
File Handling Ques-Ans
Q.3. What is the difference between Text File and Binary File?
Ans.
TEXT FILE BINARY FILE
Data is stored in ASCII format that is Data is stored in binary form (0s an 1s), that
human readable. is not human readable.
It has an EOL character that terminates It stores data as a stream of bytes.
each line of data.
We can read and write from/to a text file Conversion of data from machine readable
directly using built-in functions.. form to human readable form is required
before reading and writing in binary file.
Q.5. What is the difference between read(), readline() and readlines() function.
Ans.
read() readline() readlines()
This method reads the entire This method reads a line as This method returns the
content of the file. string and returns it. entire content of the file.
This method reads the file This method also reads the This method returns a list of
data and returns a string. new line character. strings, each separated by
It returns an empty string It returns an empty string \n.
when end of file is reached. when end of file is reached. It returns an empty string
when end of file is reached.
read(size) This method reads
specific quantity of data.
If the size is not provided or
a negative value is provided
then entire file will be read.
Q.6. What is the difference between write() and writelines() function.
Ans.
write() writelines()
This method is used to write string type This method is used to write sequence
data in a text file. To store numeric values data type such as list, tuple, etc. in a text
we have to convert it into string type. file. It can also be used to write strings.
Q.9. What are the valid from_what values used with Seek() function. Also, state the
reference point they refer to.
Ans. The from_what values used with Seek() function are 0,1,2.
Here, 0 refers to the beginning of the file (default value),
1 refers to the current position of file and
2 refers to the end of the file.
NOTE : Some valid examples of seek () function
f.seek(20,0) f.seek(-10,2) f.seek(20,1) f.seek(-20,1)
Some
invalid examples of seek () function
f.seek(-20,0) f.seek(10,2)
Q.10. What is Pickle module?
Ans. Pickle module is used in serialization of data. This allows us to store data in binary form
in the file. It uses dump and load functions write data and read data from binary file.
Pickle module allows to store any kind of object in file as it allows to store python
objects with their structure.
Q.15. What happens if we reassign a file object to some other file, without closing the file.
Ans. When we reassign a file object to some other file, then python will automatically close
the file.