Django

Working with Files

Working with Files in Python: Reading and Writing Made Easy

In programming, you often need to save data permanently or read data from files. Python provides simple and powerful tools to work with files — whether you want to read a text file, write logs, or process data.

This guide will introduce you to the basics of file handling in Python.


Basic File Operations

Python uses the built-in open() function to open files. When you open a file, you get a file object that lets you read, write, or modify the file.


Opening a File

Syntax:

python
file = open("filename.txt", "mode")
  • "r" — read (default mode)

  • "w" — write (creates or overwrites file)

  • "a" — append (add to end of file)

  • "b" — binary mode (used with other modes, e.g., "rb")


Reading from a File

Example: Read the entire file

python
with open("example.txt", "r") as file:
content = file.read()
print(content)
  • Using with automatically closes the file after the block finishes — best practice!

  • .read() reads the whole file as a string.

Read line by line

python
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # .strip() removes extra newline characters

✍️ Writing to a File

Overwrite or create a file

python
with open("output.txt", "w") as file:
file.write("Hello, world!\n")
file.write("This is a new line.\n")

This will create output.txt or overwrite it if it exists.

Append to a file

python
with open("output.txt", "a") as file:
file.write("Appending this line.\n")

️ Other Useful Methods

  • .readline() — reads one line at a time.

  • .readlines() — reads all lines into a list.

Example:

python
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)

⚠️ Important Tips

  • Always use with open(...) to ensure files are properly closed.

  • Be careful with write mode "w" — it overwrites existing files.

  • Use binary mode ("rb", "wb") for non-text files like images.


Summary

Operation Mode Description
Read "r" Open file for reading
Write "w" Open file for writing (overwrite)
Append "a" Open file to add data at the end
Binary read "rb" Read non-text files
Binary write "wb" Write non-text files

Leave a Reply

Your email address will not be published. Required fields are marked *