Lecture

File Reading and Writing

Python allows you to read from and write to text files using the built-in open() function.

This is useful for saving data to a file or loading it back later.


1. Opening a File

Use open(filename, mode) to work with a file.

  • "r" = read (default)
  • "w" = write (overwrites file)
  • "a" = append (adds to the end)
  • "x" = create (fails if file already exists)

Always close a file after using it — or better yet, use a with block to handle this automatically.


2. Reading a File

Open a file in "r" mode to read its contents.

Reading a File
with open("greeting.txt", "r") as file: content = file.read() print(content)
  • The with statement ensures the file closes automatically.
  • The read() method loads the entire file into a single string.

3. Writing to a File

Open a file in "w" mode to create or overwrite it.

Writing to a File
with open("note.txt", "w") as file: file.write("This is a new line.")
  • The "w" mode creates the file or replaces its content.
  • Use the write() method to add text to the file.

4. Appending to a File

Open a file in "a" mode to add new content without removing existing data.

Appending to a File
with open("note.txt", "a") as file: file.write("\nThis line is added.")
  • The "a" mode preserves existing content and writes new text at the end.

Summary

ModeDescription
"r"Read only mode
"w"Write mode (overwrites file)
"a"Append mode (adds to end of file)
"x"Create mode, error if it exists
Quiz
0 / 1

How do you automatically ensure a file is closed after reading its contents in Python?

To automatically close a file in Python after reading, use the block.
try-except
def
with
loop

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result