Python Tutorials · File Handling

Python File Handling

Learn all about Python File Handling in this comprehensive tutorial.

5 min read intermediate
  • File handling is an important part of any web application.
  • The key function for working with files in Python is the open() function.
  • To open a file for reading it is enough to specify the name of the file:

Introduction

File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.

File Handling

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

In addition you can specify if the file should be handled as binary or text mode

Syntax

To open a file for reading it is enough to specify the name of the file:

python

The code above is the same as:

python

Because "r" for read, and "t" for text are the default values, you do not need to specify them.

Note: Note: Make sure the file exists, or else you will get an error.

Module quiz

2 questions
1

Which of the following is true about Python File Handling?

2

What is the most common pitfall when working with Python File Handling?

Answer all questions to submit.