DEV Community

Cover image for File Handling – Day 12
augustineowino357-design
augustineowino357-design

Posted on • Edited on

File Handling – Day 12

File Handling

In the previous lesson, we learned about Exception Handling and how Python manages errors during program execution. Today, we will learn about File Handling, which allows Python programs to create, read, write, and manage files.

File Handling is important because many real-world applications store data permanently in files instead of temporary memory.


What is File Handling?

File Handling is the process of working with files such as:

  • Text files
  • CSV files
  • Log files
  • Configuration files

Python provides built-in functions for creating, reading, updating, and deleting files.


Why File Handling is Important

File Handling helps programmers:

  • Store data permanently
  • Save user information
  • Read existing data
  • Generate reports
  • Process large amounts of information
  • Build real-world applications

Opening a File

Python uses the "open()" function to open files.

Syntax

open("filename", "mode")


File Modes in Python

Mode| Meaning
""r""| Read
""w""| Write
""a""| Append
""x""| Create
""b""| Binary mode
""t""| Text mode


Reading a File

The ""r"" mode is used to read a file.

Example

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

print(file.read())
Enter fullscreen mode Exit fullscreen mode

file.close()


read()

The "read()" method reads the entire file content.

Example

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

content = file.read()

print(content)
Enter fullscreen mode Exit fullscreen mode

file.close()

readline()

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

Example

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

print(file.readline())

file.close()
Enter fullscreen mode Exit fullscreen mode

Writing to a File

The ""w"" mode writes data to a file.

If the file exists, its content is replaced.

Example

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

file.write("Welcome to Python Programming")

file.close()
Enter fullscreen mode Exit fullscreen mode

Appending to a File

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

Example

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

file.write("\nPython is powerful")

file.close()
Enter fullscreen mode Exit fullscreen mode

Creating a File

The ""x"" mode creates a new file.

Example

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

file.close()
Enter fullscreen mode Exit fullscreen mode

If the file already exists, Python raises an error.


Closing Files

The "close()" method closes a file after use.

Example

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

print(file.read())

file.close()
Enter fullscreen mode Exit fullscreen mode

Closing files helps:

  • Save resources
  • Prevent memory leaks
  • Protect file data

Using with Statement

The "with" statement automatically closes files after use.

Example

with open("data.txt", "r") as file:
    print(file.read())
Enter fullscreen mode Exit fullscreen mode

This is the recommended way to handle files in Python.


Checking if a File Exists

Python can check file existence using the "os" module.

Example

import os

if os.path.exists("data.txt"):
    print("File exists")
else:
    print("File not found")
Enter fullscreen mode Exit fullscreen mode

Deleting a File

Python can delete files using the "os.remove()" method.

Example

import os

os.remove("data.txt")
Enter fullscreen mode Exit fullscreen mode

Handling File Exceptions

File operations may produce errors such as:

  • File not found
  • Permission denied
  • Invalid file name

Example

try:
    file = open("missing.txt", "r")

    print(file.read())

except FileNotFoundError:
    print("File does not exist")
Enter fullscreen mode Exit fullscreen mode

Output

File does not exist
Enter fullscreen mode Exit fullscreen mode

Simple File Writing Program

Example

name = input("Enter your name: ")

with open("students.txt", "a") as file:
    file.write(name + "\n")

print("Data saved successfully")
Enter fullscreen mode Exit fullscreen mode

Advantages of File Handling

File Handling helps applications:

  • Save permanent data
  • Manage records
  • Store reports
  • Handle user information
  • Process files efficiently

Most software systems rely heavily on File Handling.


Conclusion

File Handling is an essential part of Python programming because it allows programs to store and retrieve data permanently.

Understanding file operations such as reading, writing, appending, and deleting files is important for building real-world applications.

Practice working with text files to improve your Python programming skills.

Python #PythonForBeginners #CodingJourney #LearnPython #Programming

Top comments (0)