MyInternships.in

Python Files & Errors

Python File Handling

File handling lets your Python program save data to disk and read it back later, so information survives after the program ends. It all starts with the built-in open() function.


Why File Handling Matters

Every variable in a running program lives only in memory — the moment the script ends, that data disappears. Files solve this by storing text or bytes on disk. Whether you are logging errors, saving user data, reading a CSV of student marks, or building a config system, file handling is the bridge between your program and permanent storage.

Opening a File

Python opens files with the open() function, which takes a file path and a mode string, and returns a file object you can read from or write to.

Basic open and close
Python
file = open("notes.txt", "r")
content = file.read()
print(content)
file.close()

File Modes

The second argument to open() is the mode — it tells Python what you plan to do with the file and whether it holds text or raw bytes. Picking the wrong mode is a common beginner mistake, like opening a file in "w" mode and accidentally erasing its contents.

ModeMeaningIf file does not existIf file exists
rRead (default)Raises FileNotFoundErrorReads from the start
wWriteCreates a new fileOverwrites (erases old content)
aAppendCreates a new fileAdds new data at the end
xExclusive createCreates a new fileRaises FileExistsError
bBinary (combine, e.g. "rb")Reads/writes raw bytes, not textUsed for images, PDFs, etc.
Different modes in action
Python
# Create or overwrite a text file
f = open("log.txt", "w")
f.write("Program started\n")
f.close()

# Append without erasing
f = open("log.txt", "a")
f.write("User logged in\n")
f.close()

# Read binary data, e.g. an image
f = open("photo.jpg", "rb")
data = f.read()
f.close()
⚠️

Opening a file in "w" mode instantly wipes its existing content. Use "a" (append) if you want to keep what is already there.

Always Close Your Files

Calling close() releases the operating system resource tied to the file and makes sure everything you wrote is actually flushed to disk. Forgetting to close files can lead to data loss or "too many open files" errors in bigger programs. Most Python developers avoid this problem entirely by using the with statement, covered in the next lesson.

  • open(path, mode) returns a file object.
  • Text mode ("t", the default) reads/writes str; binary mode ("b") reads/writes bytes.
  • Always call close(), or better, use with (next topic) to close automatically.
  • Relative paths are resolved against the current working directory.
💡

You can combine mode letters, like "rb" for reading binary or "w+" for read-and-write, overwriting the file.

Frequently Asked Questions

What is the default mode of open() in Python?+

If you omit the mode, Python uses "rt" — read, text mode. So open("file.txt") is the same as open("file.txt", "r").

What happens if I open a file that does not exist in read mode?+

Python raises a FileNotFoundError. Use "w", "a", or "x" mode instead if you want Python to create the file, or wrap the read in a try/except to handle the error gracefully.

What is the difference between "w" and "x" mode?+

"w" always succeeds — it creates a new file or overwrites an existing one. "x" (exclusive create) only succeeds if the file does not already exist; otherwise it raises FileExistsError, which protects you from accidentally overwriting data.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships