Interview question
What are the different file open modes in Python? Python में file open modes क्या-क्या हैं?
Answer
| Mode | Meaning |
|---|---|
| 'r' | Read (default) - error if file doesn't exist |
| 'w' | Write - creates file, TRUNCATES (erases) existing content |
| 'a' | Append - creates file if missing, writes at the end |
| 'x' | Exclusive creation - errors if file already exists |
| 'b' | Binary mode suffix (e.g. 'rb', 'wb') |
| '+' | Read and write suffix (e.g. 'r+', 'w+') |
with open('data.txt', 'r') as f:
content = f.read()
with open('data.txt', 'w') as f:
f.write('New content') # WARNING: erases everything that was there before
with open('data.txt', 'a') as f:
f.write('\nAppended line') # adds to the end, keeps existing content
with open('image.png', 'rb') as f:
binary_data = f.read() # bytes, not str
with open('new_file.txt', 'x') as f:
f.write('Created fresh') # FileExistsError if new_file.txt already exists| Mode | अर्थ |
|---|---|
| 'r' | Read (default) - file न हो तो error |
| 'w' | Write - existing content TRUNCATE (erase) करता है |
| 'a' | Append - अंत में लिखता है, existing रखता है |
| 'x' | Exclusive creation - पहले से हो तो error |
| 'b' | Binary mode (जैसे 'rb', 'wb') |
with open('data.txt', 'r') as f:
content = f.read()
with open('data.txt', 'w') as f:
f.write('New content') # सावधान: पुराना सब erase होगा
with open('data.txt', 'a') as f:
f.write('\nAppended line')
with open('image.png', 'rb') as f:
binary_data = f.read()Was this answer clear?