6 Myths About File Handling in Python – open() and close() Functions Exposed
File Handling in Python is the process of creating, opening, reading, writing and closing files using built-in- functions. It allows a program to store data permanently in a file rather than just in memory. Python provides easy to use functions like open() and close() functions to work with files. Mastering file handling in python ensures safe and professional coding practices.
A) File handling in python : open() operation
- Python language provides a built-in-function open() to open a file. Following is the syntax of the function:
open(filename,[mode,[encoding]])
- This function, by default, opens a file in text and read-only mode.
- On success, the function returns a file object. This object is defined in the io module.
- The file object provides the relevant APIs for file manipulation.
Common Errors –
- Throws FileNotFoundError when the files is not found.
- Throws PermissionError when you do not have the required permission to open a file.
- Write operation on read-only file throws io.UnsupportedOperation error.
Encoding –
Use encoding to open a file in a particular format.
- Cp1252 is the default format on Windows.
- UTF-8 supports Unicode characters.
B) File handling in python : close() operation
.The file handling in python object, which we get when a file opens successfully, provides the close() method.
- When a file is closed, it flushes the data from memory to file and closes it.
- It is important to close the file after using it.
- It is possible to edit a file only when it is open exclusively in write mode by a program.
- So if you leave files open, it may hinder the write operation(s).
Code Example – File Open and Close Operation :
fHandle = open(“.\\files\\sample.txt”)
print(fHandle)
fHandle.close()
Output –
<_io.TextIOWrapper name=’.\\files\\sample.txt’ mode=’r’ encoding=’cp1252′>
This confirms that the file is successfully opened in read-only mode.
File Not Found Error – Example :
fHandle = open(“.\\files\\sampleee.txt”) # Incorrect file name
Output-
FileNotFoundError: [Errno 2] No such file or directory: ‘.\\files\\sampleee.txt’
This error occurs because the file name is incorrect or the file doesn’t exist in the specified path.
Summary :-
| Operation | Function | Description |
| Open File | open() | Opens a file in read or other modes |
| Close File | close() | Closes the opened file and frees resources |
| Common error | File Not Found Error | Raised when the file does not exist |
| Default Encoding | Cp1252(Windows) | File is read in text mode |
C) 6 Myths About File Handling-open() and close() Functions Exposed
When working with file handling in Python, the open() and close() functions are two basic tools that every beginner learns early. But despite being so common, file handling often remains misunderstood. Many learners assume things that simply aren’t true — and these myths can lead to bugs, data loss, or even security issues.
Let’s dive into the 6 most common myths about Python file handling and uncover the real story behind open() and close().
Myth 1: In file handling in python, open() can only open files in read mode
Reality:
While it’s true that open() defaults to read mode (‘r’), it can actually open files in a variety of modes — for reading, writing, appending, and even binary operations.
Common Modes in Python:
| Mode | Description |
| ‘r’ | Read-only(default), file must exist |
| ‘w’ | Write mode, creates or overwrites file |
| ‘a’ | Append mode, adds content at the end |
| ‘r+’ | Read and write both |
| ‘rb’ | Read binary |
| ‘wb’ | Write binary |
Example:
python
Copy
file = open(“example.txt”, “w”)
file.write(“Hello World!”)
file.close()
So no — open() is not limited to just reading. You have control.
Myth 2: In file handling in python, close() is optional – Python will handle it
Reality:
Although file handling in Python might eventually close the file when the program ends, it’s not something you should rely on. If you don’t close the file manually:
- Data might not be saved to disk (especially in ‘w’ or ‘a’ mode).
- Resources may not be released immediately.
- In larger scripts, unclosed files can cause memory leaks or file lock errors.
Good Practice:
python
Copy
file = open(“log.txt”, “a”)
file.write(“Session started\n”)
file.close()
Even better? Use with, which we’ll discuss in Myth 6.
Myth 3: If the file doesn’t exist, open() will create it
Reality:
This depends on the mode you use:
- ‘w’ and ‘a’ will create the file if it doesn’t exist.
- ‘r’ and ‘r+’ will not — and they’ll raise a FileNotFoundError.
Wrong:
python
Copy
f = open(“notes.txt”) # File doesn’t exist – this will crash
Right:
python
Copy
f = open(“notes.txt”, “w”) # This will create the file
Always choose the mode carefully depending on whether the file already exists.
Myth 4: You can write to a file opened in default mode
Reality:
The default mode is ‘r’, which is strictly for reading. If you try to use .write() in this mode, Python will raise an io .Unsupported Operation error.
Allowed modes for writing:
- ‘w’ (write)
- ‘a’ (append)
- ‘r+’ (read/write)
Example:
python
Copy
f = open(“data.txt”, “w”)
f.write(“Adding new data.”)
f.close()
Don’t forget to always close the file or use with.
Myth 5: Encoding doesn’t matter while working with files
Reality:
Encoding is very important, especially when your file contains non-English or special characters like ₹, é, or emoji. Python defaults to platform-based encoding (cp1252 on Windows), which might not handle Unicode well.
To avoid weird characters or errors like UnicodeDecodeError, explicitly use encoding=’utf-8′.
Example:
python
Copy
f = open(“report.txt”, “r”, encoding=”utf-8″)
data = f.read()
f.close()
Myth 6: It’s okay to leave files open in small programs
Reality:
Leaving a file open — even in a small script — is never a good idea. It may not cause a crash right away, but it’s still using system resources and may block other operations (like opening the same file elsewhere).
Best Practice: Use the with statement
python
Copy
with open(“log.txt”, “r”) as f:
data = f.read()
# No need to call close(); it’s done automatically
Using with ensures the file is always closed properly — even if an error occurs during file reading or writing.
Summary Table:-
| Myth No. | Belief | Reality |
| 1. | open() only opens in read mode | It supports multiple modes like ‘w’ ,’a’,’r+’ |
| 2. | close() isn’t necessary | Always close files or use with to avoid issues |
| 3. | open() creates the file if it’s missing | Only in ‘w’ or ‘a’ mode, not in ‘r’ |
| 4. | You can write in default mode | Writing allowed only in ‘w’,’a’,or ‘r+’ |
| 5. | Encoding doesn’t matter | Always prefer utf-8 for safer file handling |
| 6. | Small programs don’t need file closing | Leaving files open is a bad practice in all cases |
Visit the official Python documentation
More helpful Python tutorials coming soon on this blog .Stay tuned !
Conclusion
file handling in python for this fuction. Don’t let these common myths stop you from mastering file handling in Python. Whether you’re reading a config file or logging data in a loop, understanding how open() and close() truly work is key to writing safe and professional code. By learning proper techniques of file handling in python, you can avoid common mistake and write cleaner code.