Skip to content
Exercises · Q1

Q.Differentiate between:

a) text file and binary file
b) readline() and readlines()
c) write() and writelines()
Uttar Pradesh UpmspTextbookSubjective· 3mImportance★★★★★
23% · 5/22 Questions
✓ Free question

This question tests your understanding of Python file handling methods — specifically the differences between file types (text vs binary) and between reading/writing methods (readline() vs readlines(), write() vs writelines()). Each comparison highlights a different aspect: data representation, return type, or argument handling.

This is a plain theory question — three separate comparisons, each requiring a clear conceptual distinction. Let's take them one at a time.


(a) Text file vs Binary file

The fundamental difference lies in how data is stored and interpreted.

A text file stores data as a sequence of characters (human-readable). When you open it, Python decodes the bytes into strings using a character encoding (usually UTF-8). Every character — including newline \n — is treated as a text element. Examples: .txt, .py, .csv, .html.

A binary file stores data as raw bytes — no encoding, no character interpretation. The file contains the exact sequence of bytes as they exist in memory. When you open it, you read and write bytes objects, not strings. Examples: .jpg, .mp3, .exe, .dat.

Watch out

A common mistake is to open a binary file in text mode (or vice versa). Opening a binary file in text mode will corrupt the data because Python will try to decode arbitrary bytes as text, often raising a UnicodeDecodeError. Always use 'b' in the mode string for binary files: open('image.jpg', 'rb').

FeatureText fileBinary file
Data representationCharacters (strings)Raw bytes
Open mode'r', 'w', 'a''rb', 'wb', 'ab'
Read/write typestrbytes
EncodingRequired (default UTF-8)Not applicable
Human-readableYesNo
Newline handling\n translated per OSNo translation

(b) readline() vs readlines()

Both methods read from a text file opened in read mode, but they differ in what they return.

readline() reads one line at a time, including the trailing newline character. It returns a single string. If the file is empty or you've reached the end, it returns an empty string ''. You typically use it in a loop when you want to process each line individually without loading the entire file into memory.

with open('data.txt', 'r') as f:
    line = f.readline()
    while line:
        print(line.strip())  # strip() removes the \n
        line = f.readline()

readlines() reads all lines at once and returns a list of strings, where each string is one line (including its newline). This is convenient when you need random access to lines or want to process the entire file quickly, but it loads the whole file into memory — problematic for very large files.

with open('data.txt', 'r') as f:
    lines = f.readlines()
    for i, line in enumerate(lines):
        print(f"Line {i+1}: {line.strip()}")
Tip

For most cases, you can simply iterate over the file object directly: for line in f: — this is memory-efficient like readline() but cleaner in syntax. Use readlines() only when you genuinely need a list (e.g., to index lines or pass to a function expecting a list).

MethodReturn typeReadsMemory usage
readline()Single strOne line at a timeLow (one line)
readlines()list of strAll lines at onceHigh (entire file)

(c) write() vs writelines()

Both methods write to a file opened in write or append mode, but they differ in what arguments they accept.

write() takes a single string (or bytes, for binary mode) and writes it to the file. It returns the number of characters written. You must explicitly add newline characters if you want line breaks.

with open('output.txt', 'w') as f:
    f.write("First line\n")
    f.write("Second line\n")

writelines() takes an iterable of strings (typically a list or tuple) and writes each string to the file without adding any separators or newlines. This is a common point of confusion: despite the name, writelines() does not automatically append newlines. You must ensure each string in the iterable already contains the newline character if you want line breaks.

lines = ["First line\n", "Second line\n", "Third line\n"]
with open('output.txt', 'w') as f:
    f.writelines(lines)
Watch out

The most frequent mistake with writelines() is expecting it to add newlines automatically. It does not. If your list elements don't end with \n, everything will be written on one line. Always check your data before calling writelines().

MethodArgumentAdds newlines?Returns
write()Single strNo (you add them)Number of chars written
writelines()Iterable of strNo (you add them)None

✓Final answer

(a) Text files store human-readable characters with encoding; binary files store raw bytes without encoding. (b) readline() returns one line as a string; readlines() returns all lines as a list of strings. (c) write() writes a single string; writelines() writes an iterable of strings (no automatic newlines).

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.