Skip to content

Computer Science · Ch 2 — File Handling in Python

Summary

Summary

  • 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 — alphabets, numbers, and other special symbols — 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 the ASCII equivalents of its characters and is terminated by a special character, called the End of Line (EOL).
  • A binary file consists of data stored as a stream of bytes.
  • open() is used to open a file in Python and it returns a file object called a file handle. The file handle is used to transfer data to and from the file by calling the functions defined in Python's io module.
  • close() 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() takes a string as an argument and writes it to the text file.
  • writelines() is used to write multiple strings to a file. You need to pass an iterable object, like a list or tuple, containing strings to the writelines() method.
  • read([n]) is used to read a specified number of bytes (n) of data from a data file.
  • readline([n]) reads one complete line from a file where lines end with a newline (\n). It can also be used to read a specified number (n) of bytes of data from a file, but at most up to the newline character (\n).
  • readlines() reads all the lines and returns the lines, along with the newline character, as a list of strings. …