File Handling

Learn to read, write, and manage files to save data permanently.

Learn Python, JavaScript, Java and more with free interactive lessons, real projects and AI-powered help. Beginner-friendly.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

When your program ends, all variables are lost. Files let you save data permanently so it survives after your program closes.

Use the open() function to work with files. You specify the filename and a mode that tells Python what you want to do.

Always use the with statement when working with files. It automatically closes the file when you are done, even if an error occurs.

Use mode "w" to write to a file. This creates a new file or overwrites an existing one.

Use mode "a" to add content to the end of a file without deleting existing content.

Before reading a file, check if it exists to avoid errors:

Use try-except to handle errors gracefully when working with files:

CSV (Comma-Separated Values) is a common format for spreadsheet data. Python has a built-in csv module to work with it.

JSON (JavaScript Object Notation) is used for configuration files and APIs. Python can easily convert between JSON and dictionaries.

Lesson 9 complete — your programs can now save and load data!

Reading, writing, appending, CSV, JSON — you know how to work with files safely using the with statement. Your programs can now remember things between runs.

🚀 Up next: Exception Handling — learn to catch errors gracefully so your programs never crash unexpectedly.

Practice quiz

Which file mode opens a file for reading (and errors if it doesn't exist)?

  • "w"
  • "a"
  • "r"
  • "x"

Answer: "r". Mode "r" opens for reading; the file must already exist.

What does opening a file in mode 'w' do to existing content?

  • Appends to the end
  • Overwrites (deletes) it
  • Raises an error
  • Leaves it unchanged

Answer: Overwrites (deletes) it. Mode "w" creates a new file or overwrites an existing one, deleting its content.

Which mode adds to the end of a file without deleting existing content?

  • "a"
  • "w"
  • "r"
  • "x"

Answer: "a". Mode "a" (append) keeps existing content and adds to the end.

Why is 'with open(...) as file:' the recommended way to handle files?

  • It runs faster
  • It automatically closes the file, even if an error occurs
  • It allows multiple modes at once
  • It compresses the file

Answer: It automatically closes the file, even if an error occurs. The with statement auto-closes the file when the block ends, even on errors.

What does the .read() method return?

  • A list of lines
  • One line at a time
  • The entire file as one string
  • The number of characters

Answer: The entire file as one string. .read() returns the whole file content as a single string.

Which method returns a list of all lines in a file?

  • .read()
  • .readline()
  • .readlines()
  • .lines()

Answer: .readlines(). .readlines() returns a list where each element is one line.

Does .write() automatically add a newline at the end of each call?

  • Yes, always
  • No, you must add yourself
  • Only in append mode
  • Only for the first line

Answer: No, you must add yourself. .write() does not add line breaks; you add yourself for separate lines.

Which exception is raised when reading a file that doesn't exist?

  • FileNotFoundError
  • PermissionError
  • ValueError
  • KeyError

Answer: FileNotFoundError. Reading a missing file raises FileNotFoundError.

Which function checks whether a file exists before opening it?

  • os.exists()
  • os.path.exists()
  • file.exists()
  • os.check()

Answer: os.path.exists(). os.path.exists('file.txt') returns True if the path exists.

Which json function reads a JSON file directly into a Python object?

  • json.loads(str)
  • json.dumps(obj)
  • json.load(file)
  • json.dump(obj, file)

Answer: json.load(file). json.load(file) reads from an open file object into Python; loads is for strings.