File Handling – Notes

  • A file is a named location on a secondary storage media where data are permanently stored for later access.
  • A text file contains only textual information consisting of alphabets, numbers and other special symbols. Such files are stored with extensions like .txt, .py, .c, .csv, .html, etc. Each byte of a text file represents a character.
  • Each line of a text file is stored as a sequence of ASCII equivalent of the characters and is terminated by a special character, called the End of Line (EOL).
  • Binary file consists of data stored as a stream of bytes.
  • open() method is used to open a file in Python and it returns a file object called file handle. The file handle is used to transfer data to and from the file by calling the functions defined in the Python’s io module.
  • close() method is used to close the file. While closing a file, the system frees up all the resources like processor and memory allocated to it.
  • write() method takes a string as an argument and writes it to the text file.
  • writelines() method is used to write multiple strings to a file. We need to pass an iterable object like lists, tuple etc. containing strings to writelines() method.
  • read([n]) method is used to read a specified number of bytes (n) of data from a data file.
  • readline([n]) method reads one complete line from a file where lines are ending with a newline (\n). It can also be used to read a specified number (n) of bytes of data from a file but maximum up to the newline character (\n).
  • readlines() method reads all the lines and returns the lines along with newline character, as a list of strings.
  • tell() method returns an integer that specifies the current position of the file object. The position so specified is the byte position from the beginning of the file till the current position of the file object.
  • seek()method is used to position the file object at a particular position in a file.
  • Pickling is the process by which a Python object is converted to a byte stream.
  • dump() method is used to write the objects in a binary file.
  • load() method is used to read data from a binary file.

Leave a Comment

You cannot copy content of this page

Scroll to Top