Computer Science
Write the use and syntax for the following methods:
- open()
- read()
- seek()
- dump()
Python File Handling
7 Likes
Answer
open() — The open() method opens the given file in the given mode and associates it with a file handle. Its syntax is
file_object = open(file_name, access_mode)
.read() — The read() method is used to read data from a file object. It reads at most 'n' bytes from the file, where 'n' is an optional parameter. If no 'n' is specified, the read() method reads the entire contents of the file. Its syntax is:
file_object.read(n)
.seek() — This method is used to position the file object at a particular position in a file. Its syntax is:
file_object.seek(offset [, reference_point])
.dump() — This method is used to convert (pickling) Python objects for writing data in a binary file. Its syntax is :
dump(data_object, file_object)
.
Answered By
3 Likes
Related Questions
Differentiate between readline() and readlines().
Differentiate between write() and writelines().
Write the file mode that will be used for opening the following files. Also, write the Python statements to open the following files:
- a text file “example.txt” in both read and write mode.
- a binary file “bfile.dat” in write mode.
- a text file “try.txt” in append and read mode.
- a binary file “btry.dat” in read only mode.
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 ?