Interview question
What is the difference between text mode and binary mode when working with files? Files के साथ काम करते समय text mode और binary mode में क्या अंतर है?
Answer
| Mode | Data returned | Handles |
|---|---|---|
| Text mode ('r', 'w') | str | Automatic encoding/decoding, newline translation |
| Binary mode ('rb', 'wb') | bytes | Raw bytes, no encoding/decoding or newline translation |
# Text mode - automatically decodes bytes to str using an encoding
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(type(content)) # <class 'str'>
# Binary mode - raw bytes, no decoding
with open('image.png', 'rb') as f:
content = f.read()
print(type(content)) # <class 'bytes'>
# Attempting text mode on a binary file often raises UnicodeDecodeError
# with open('image.png', 'r') as f:
# f.read() # UnicodeDecodeError: invalid start byte
# Explicitly specifying encoding avoids platform-dependent default encoding issues
with open('data.txt', 'r', encoding='utf-8') as f: # always specify encoding explicitly
content = f.read()
# Writing bytes
with open('output.bin', 'wb') as f:
f.write(b'\x00\x01\x02') # bytes literal, prefixed with b
# Converting between str and bytes manually
text = 'Hello'
encoded = text.encode('utf-8') # str -> bytes
decoded = encoded.decode('utf-8') # bytes -> str
print(encoded) # b'Hello'
print(decoded) # Hello| Mode | Data type | क्या handle करता है |
|---|---|---|
| Text mode ('r', 'w') | str | Automatic encoding/decoding |
| Binary mode ('rb', 'wb') | bytes | Raw bytes, कोई encoding नहीं |
# Text mode - automatically str में decode करता है
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(type(content)) # str
# Binary mode - raw bytes
with open('image.png', 'rb') as f:
content = f.read()
print(type(content)) # bytes
# Encoding explicitly specify करना अच्छी practice है
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read()
# Bytes लिखना
with open('output.bin', 'wb') as f:
f.write(b'\x00\x01\x02')
# str और bytes के बीच manually convert करना
text = 'Hello'
encoded = text.encode('utf-8') # str -> bytes
decoded = encoded.decode('utf-8') # bytes -> str
print(encoded) # b'Hello'Was this answer clear?