Lesson 43 of 70 – File Handling
61%

Python File Handling

File handling in Python allows us to create, open, read, write, update, and delete files. File handling is useful when data needs to be stored permanently instead of keeping it only in program memory.

Note: Python provides the built-in open() function for working with files.
What is File Handling?

File handling means performing operations on files using a programming language.

Common file operations include:

  • Creating a file
  • Opening a file
  • Reading a file
  • Writing to a file
  • Appending data
  • Updating file contents
  • Closing a file
  • Deleting a file
Why Use Files?

Variables store data temporarily while a program is running. Files can store data so that it can remain available after the program finishes.

For example:

name = "Amit"

The value is stored in memory while the program runs. A file can be used when the data needs to be saved for later use.

The open() Function

The open() function is used to open a file.

Basic syntax:

open("filename", "mode")

Example:

file = open("data.txt", "r")

Here, data.txt is the file name and r means read mode.

File Opening Modes
Mode Meaning
r Read an existing file.
w Write to a file. Creates it if needed and replaces existing content.
a Append data to the end of a file.
x Create a new file and fail if it already exists.
b Binary mode.
t Text mode.
+ Update mode for reading and writing.
Reading a File

The read() method reads the contents of a file.

file = open("data.txt", "r")

content = file.read()

print(content)

file.close()

The close() method closes the file after the operation is complete.

Writing to a File

The w mode allows us to write data to a file.

file = open("data.txt", "w")

file.write("Hello Python")

file.close()

If the file does not exist, Python creates it. If it already exists, its previous contents are replaced.

Appending to a File

The a mode adds new content to the end of an existing file.

file = open("data.txt", "a")

file.write("\nWelcome to Python")

file.close()

Unlike w mode, append mode does not replace the existing contents.

Creating a New File with x Mode

The x mode is used to create a new file.

file = open("newfile.txt", "x")

file.write("New file created")

file.close()

If the file already exists, opening it with x mode raises a FileExistsError.

Closing a File

The close() method closes an opened file.

file = open("data.txt", "r")

print(file.read())

file.close()

Closing files helps release system resources after the file operation is finished.

Checking Whether a File is Closed

The closed attribute tells whether a file object has been closed.

file = open("data.txt", "r")

print(file.closed)

file.close()

print(file.closed)
Output:
False
True
Using with to Open a File

The with statement is the recommended way to work with files in many situations.

with open("data.txt", "r") as file:

    content = file.read()

    print(content)

When the with block finishes, Python automatically closes the file.

Writing Using with
with open("data.txt", "w") as file:

    file.write("Python File Handling")

The file is automatically closed after the with block.

Reading the Entire File
with open("data.txt", "r") as file:

    data = file.read()

print(data)

The read() method returns the file contents as a string when working with a text file.

Reading a Specific Number of Characters

You can pass a number to read() to read a specific number of characters.

with open("data.txt", "r") as file:

    data = file.read(5)

print(data)

This reads up to the first five characters from the current file position.

readline()

The readline() method reads one line at a time.

with open("data.txt", "r") as file:

    line = file.readline()

    print(line)

Calling readline() again reads the next line.

readlines()

The readlines() method reads the lines of a text file and returns them as a list.

with open("data.txt", "r") as file:

    lines = file.readlines()

print(lines)
Example:
['First line\n', 'Second line\n', 'Third line\n']
Reading a File Line by Line

A file object can be iterated over directly to process one line at a time.

with open("data.txt", "r") as file:

    for line in file:
        print(line.strip())

This approach is useful when processing large text files because it does not require loading the entire file into a list first.

write()

The write() method writes a string to a file.

with open("data.txt", "w") as file:

    file.write("Hello\n")
    file.write("Welcome to Python\n")
    file.write("File Handling")

The \n character starts a new line.

writelines()

The writelines() method writes multiple strings to a file. It does not automatically add newline characters.

lines = [
    "Python\n",
    "Java\n",
    "JavaScript\n"
]

with open("languages.txt", "w") as file:

    file.writelines(lines)
File Position

Python keeps track of the current position in an opened file. The tell() method returns the current position.

with open("data.txt", "r") as file:

    print(file.tell())

The position is measured in bytes for binary streams and generally in text-stream units for text files.

seek()

The seek() method changes the current file position.

with open("data.txt", "r") as file:

    file.seek(0)

    data = file.read()

    print(data)

Using seek(0) moves the file position back to the beginning for a typical text file.

File Encoding

When working with text files, it is often a good practice to specify the encoding explicitly.

with open(
    "data.txt",
    "r",
    encoding="utf-8"
) as file:

    data = file.read()

print(data)

UTF-8 is a widely used text encoding and supports many languages.

Handling File Errors

Trying to open a missing file in read mode can raise FileNotFoundError.

try:

    with open("missing.txt", "r") as file:
        data = file.read()

except FileNotFoundError:

    print("File does not exist")
Output:
File does not exist
Text Files vs Binary Files

Python can work with both text and binary files.

Text File Binary File
Stores text data. Stores binary data.
Examples: TXT, CSV Examples: images, PDFs, executable files
Usually opened using text mode. Use b mode.

Example:

with open("image.jpg", "rb") as file:

    data = file.read()
Deleting a File

Python's os module can be used to delete a file.

import os

if os.path.exists("data.txt"):

    os.remove("data.txt")

    print("File deleted")

else:

    print("File does not exist")
Important: Deleting a file is an irreversible filesystem operation in normal use. Always make sure you are targeting the correct file.
Checking if a File Exists

The os.path.exists() function checks whether a path exists.

import os

if os.path.exists("data.txt"):

    print("File exists")

else:

    print("File does not exist")
File Handling Example

The following example creates a file, writes data to it, and then reads the data.

with open("student.txt", "w", encoding="utf-8") as file:

    file.write("Name: Rahul\n")
    file.write("Course: Python\n")
    file.write("Age: 21\n")


with open("student.txt", "r", encoding="utf-8") as file:

    data = file.read()

print(data)
Output:
Name: Rahul
Course: Python
Age: 21
Best Practices for File Handling
  • Prefer the with open() pattern for normal file operations.
  • Specify an appropriate encoding for text files when needed.
  • Handle expected file-related exceptions.
  • Use the correct file mode for the operation.
  • Avoid unnecessarily loading very large files into memory.
  • Close files when they are opened without a context manager.
  • Be careful when overwriting or deleting files.
Key Points
  • The open() function is used to work with files.
  • r is used for reading.
  • w is used for writing and can replace existing content.
  • a is used for appending.
  • x creates a new file and fails if it already exists.
  • read(), readline(), and readlines() are used for reading.
  • write() and writelines() are used for writing.
  • with open() automatically closes the file.
  • seek() changes the file position.
  • tell() returns the current file position.
  • The os module can be used for filesystem operations such as checking and deleting files.

🧠 Quick Quiz

Question: Which file mode is used to append data to the end of a file?