Python Files I/O

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

In this Python tutorial, let us see Python Files I/O with suitable examples.

Introduction of Python Files I/O

File handling is an essential part of any web application. Python has several functions for reading, writing, updating, and deleting files.

The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode.

The following four different modes used 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 exists.

Syntax

f = open("demofile.txt")
f = open("demofile.txt", "rt")

Both are same.

Opening a file

Consider the demofile.txt

demofile.txt:-
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

To open the file, use the built-in open() function.

Example

f = open("demofile.txt", "r")
print(f.read())

Output

Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

Closing a Files

It is a good practice to always close the file when you are done with it.

Example

f = open("demofile.txt", "r")
print(f.readline())
f.close()

Deleting a file

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

Example

import os
os.remove("demofile.txt")

The file demofile.txt will be deleted.

Leave a Comment

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