Python Tutorial
Python - Introduction Python - Syntax Python - Variable Python - Number Python - Casting Python - String Python - Operators Python - Conditions Python - Loops Python - List Python - Tuple Python - Set Python - Dictionary Python - Function Python - Module Python - Date & Time Python - Input Output Python - Error & Exception Python - File Handling
Python OOP
OOP - Introduction OOP - Class Members OOP - Constructor Destructor OOP - Data Hiding OOP - Inheritance OOP - Overriding OOP - Overloading

Python File Handling

File handling is an important part of any application.

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


Open a File

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:

  • r - Read - Default value. Opens a file for reading, error if the file does not exist
  • a - Append - Opens a file for appending, creates the file if it does not exist
  • w - Write - Opens a file for writing, creates the file if it does not exist
  • x - Create - Creates the specified file, returns an error if the file exist

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

  • t- Text - Default value. Text mode
  • b - Binary - Binary mode (e.g. images)

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

Make sure the file exist, or else you will get an error.


Read a File

The read() method is used to read files.

Before read a file you must open it using open() function.



Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify how many character you want to return:


Read Lines

You can return one line by using the readline() method:

By calling readline() two times, you can read the two first lines.


Write File

To write to an existing file, you must add a parameter to the open() function:

  • a - Append - will append to the end of the file
  • w - Write - will overwrite any existing content

The w method will overwrite the entire file.


Create a New File

To create a new file in Python, use the open() method, with one of the following parameters:

  • x - Create - will create a file, returns an error if the file exist
  • a - Append - will create a file if the specified file does not exist
  • w - Write - will create a file if the specified file does not exist

Python Delete Files

To delete a file, you must import the OS module, and run its os.remove() function: