LearnWave
Learn it. Master it.

File Handling in Python

Files and their types

Tell text files from binary files.

Variables keep their values only while a program is running; when it ends, the data is gone. To keep data permanently, programs store it in files on secondary storage, such as a hard disk or pen drive.

A file is a named location on secondary storage where data is permanently stored. Every file, whatever it holds, is stored as a series of bytes (0s and 1s). There are two kinds:

  • Text files hold human-readable characters: letters, digits and symbols. Each character is stored as its code in ASCII or Unicode (in ASCII, 65 stands for 'A'). Text is arranged in lines, and each line ends with a special end-of-line (EOL) character; in Python, the default EOL is \n (newline). Files ending in .txt, .py and .csv are text files, and can be opened and read in any text editor, such as Notepad.
  • Binary files hold bytes that represent images, audio, video, compressed data or executable programs. They are not human-readable: opened in a text editor, they look like meaningless symbols. They need the right software to open them. Even a single wrong bit can corrupt a binary file so that it cannot be opened.

This explains a puzzle. A one-word document saved as a .txt file takes only a few bytes: just the characters. The same word saved as a .docx (Word) file takes kilobytes, because the file also stores the author, page settings, fonts, dates and more.

Text files you can read; binary files need software.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.