You are on page 1of 2

File Handling

1. Differentiate between:
a) Text file and binary file
b) readline() and readlines()
c) write and writelines()

Ans: a) A text file is a file that stores information in the form of a stream of ASCII or
Unicode characters. In text files, each line of text is terminated with a special character
knowns as EOL
(End of line) character.

A binary file is a file that stores the information in the form of a stream of bytes. In a
binary
file, there is no delimiter for a line and no character translations occur here.

2. Name the methods which are commonly used to read data from a text file.
3. Name the methods which are commonly used to write data into a text file.
4. Define pickling, serialization and deserialization.
5. Write the use and syntax for the following methods.
a) open()
b) read()
c) seek()
d) tell()
e) dump()
6. Why is it advised to close a file after we are done with the read and write
operations? What will happen if we do not close it? Will some error message be
flashed?

Ans: It is advised to close a file after we are done with the read and write operations because
of the following reasons:

a) Closing files using close () is a good programming practice.


b) Sometimes the data written onto files using write functions is held in memory until
the next write or the file is closed. So, for the last write operation, the data
remain in memory until close () is used. This may lead to data loss sometimes.

c) Sometimes there are operating system restrictions on number of open files at


anytime. Thus, we must close our file when its work is done.

7. Write the file mode that will be used for opening the following files. Also, write
the Python statements to open the following files:
a) A text file ‘example.txt’ in both read and write
b) A binary file “bfile.dat” in write mode
c) A text file “try.txt” in append and read mode
d) A binary file “btry.dat” in read only mode.
8. What is the difference between “w” and “a” .

You might also like