Python File Handling

This tutorial cover all file handling operations available in Python such as creating, reading, updating and deleting files.

open() function is used to open the file. It takes two parameters filename and mode. There are four different modes for opening a file.

  • r  –  Read – Open a file for reading, throw an error if the file doesn’t exist. Default value
  • w – Write – Open a file for writing. Create a file if the file doesn’t exist.
  • a  – append – Open a file for appending. Create the file if the file doesn’t exist.
  • x  – Create – Create the file, throw an error if the file exists
file = open('test.txt','r')

Let’s create a test.txt file in the same directory where your Python code is located. And copy the following content in the test.txt file.

Hello World!
I am John
Good Bye!

read() function is used to read the content of the file.

file = open('test.txt','r')
print(file.read())

readline() method is used to read a single line of the file.

file = open('test.txt','r')
print(file.readline())   # Output: Hello World! 
print(file.readline())   # Output: I am John

Close Files

It is good practice to close the file using the close() method when you complete file operations.

file = open('test.txt','r')
print(file.readline())
file.close()

.     .     .

Write to 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

Example 1:

file = open('test.txt','a')
file.write("New line appended")
file.close()
#
file = open('test.txt','r')
print(file.read())
file.close()

This produces the following result:

Hello World! 
I am John 
Good Bye!New line appended

Example 2

file = open('test.txt','w')
file.write("Write new Line")
file.close()
#
file = open('test.txt','r')
print(file.read())
file.close()

This produces the following result:

Write new Line

.     .     .

Delete a File

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

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

This line throws an error if the file doesn’t exist. So, it is better to check if file exists in the directory or not before using this function.

import os
if os.path.exists("test.txt"):
  os.remove("test.txt")
else:
  print("The file does not exist")

.     .     .

Leave a Reply

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

Python Tutorials

Python – List Comprehension

Python Set

Python : Assert Keyword

Python Dictionary

Python Tuple

Python List

Python: String

Python: String Formatting using f-string

Python: String Formatting – 2

Python: String Formatting – 1

Python Input/Output

Python Type Conversion and Type Casting

Python Comments

Python – Regular Expression (RegEx)

Python Iterators

Python Exceptions

Python Function

Python Loops

Python If…Else

Python Collections

Python Operators

Variables in Python

Python Syntax

Introduction to Python

Python OOPs Concepts