Skip to main content
Practice

File Reading and Writing (Text Files)

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

This is useful when you want to save data to a file or load data from one.


1. Opening a File

Use open(filename, mode) to access a file.

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

Always close the file after using it, or use a with block.


2. Reading a File

with open("greeting.txt", "r") as file:
content = file.read()
print(content)

Explanation:

  • with ensures the file closes automatically.
  • file.read() reads the entire file content as a string.

3. Writing to a File

with open("note.txt", "w") as file:
file.write("This is a new line.")

Explanation:

  • "w" mode creates the file or overwrites it.
  • Use file.write() to add content.

4. Appending to a File

with open("note.txt", "a") as file:
file.write("\nThis line is added.")

Explanation:

  • "a" mode adds new content without deleting existing data.

Summary

ModeDescription
"r"Read only
"w"Write (overwrite)
"a"Append to file
"x"Create file, error if it exists

What’s Next?

Next, you’ll learn how to work with CSV files, which are commonly used to store structured data like spreadsheets.