Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 8 of 10 · File Handling & Context Managers
Interview question

What is the difference between text mode and binary mode when working with files? Files के साथ काम करते समय text mode और binary mode में क्या अंतर है?

Answer
ModeData returnedHandles
Text mode ('r', 'w')strAutomatic encoding/decoding, newline translation
Binary mode ('rb', 'wb')bytesRaw 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
ModeData typeक्या handle करता है
Text mode ('r', 'w')strAutomatic encoding/decoding
Binary mode ('rb', 'wb')bytesRaw 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?