File Handling in Python with Examples

In this article we are going to cover File Handling in Python with Examples, Read files in python, Create Files in Python, write file in Python, write to file in Python, Delete a File in Python and remove folder in Python.

File Handling in Python

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

When we want to read from or write to a file, we need to open it first. When we are done, it needs to be closed so that the resources that are tied with the file are freed.

Steps used during file handling in python:

  1. Opening a file to write.
  2. Read or Write.
  3. Close the file.

File Handling : Opening

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

There are four different methods for opening a file:

“r” – Read – If you want to read from a file.

“w” – Write – If you want to write to a file erasing completely previous data.

“a” – Append – If you want to append to previously writtrn file.

“x” – create  – If you want just to create a file.

Additional used modes to specify the type of file is:

  1. “t” – Text – text file, Default value.
  2. “b” – Binary – binary file. (e.g. images)

Syntax:

file = open(“filename.txt”) 

Another Syntax:

file = open(“file.png”)

The open() function returns a file object, which has a read() method for reading the content of the file

Example of Read files in python:

file = open("demofile2.txt", "r")
print(file.read())

Output:

Hello! Welcome to FOSS TechNix
File Handling in Python with Examples 1

Example of read() mode character wise in Python:

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

print(file.read(5))

Output:

Hello

In this Example we will read only first five characters only.

File Handling in Python with Examples 2

If the file is located in different location you will have to specify the file path:

Example:

file = open("C:\\file\\demofile2.txt", "r")

print(file.read())

Write or Create Files in Python:

To write a file you have to open it in write mode and then you can write. It is important to note that all previously written data will be overwritten.

Example of write or create file in python:

file = open("append.txt", "a")
file.write("This is append Example.")
file.close()

file = open ("append.txt","r")
print (file.read())

Output:

Hello! Welcome to FOSS TechNixThis is append Example.
File Handling in Python with Examples 3

Another Example of write file in Python :

In this example Open the txt file and overwrite the content

file = open("write.txt", "w")
file.write("This is read or write Example.")
file.close()

file = open ("write.txt","r")
print (file.read())

Output:

This is read or write Example.
File Handling in Python with Examples 4

Example of write to file in Python:

file = open('file.txt', 'w') 
L = ["This is Mumbai \n", "This is Nanded \n", "This is Thane \n"] 
s = "Hello\n"
file.write(s) 
file.writelines(L) 
file.close() 
 
file = open('file.txt', 'r') 
print(file.read()) 
file.close()

Output:

Hello
This is Mumbai 
This is Nanded 
This is Thane
File Handling in Python with Examples 5

Create a New File in Python:

To create a new file in Python. Use the open() method.

“x” – Create – Create a new file

“a” – Append – Create a file if the same file does not exist.

“w” – write – Create a file if the same file does not exist.

Example of create a new file in Python:  

file = open(“file.txt”, “x”)

Output:

A new empty file created.

Delete a File in Python :

If you want to delete a file, you have to import the OS module, and run as os.remove() Method.

Example of delete a file in Python:

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

Output:

File deleted.

If you want to delete entire folder then use os.rmdir() method.

Example of remove folder in Python:

import os
os.rmdir("folder")

Note: you can remove only empty folders.

Output:

Folder removed.

Conclusion:

We have covered File Handling in Python with Examples, Read files in python, Create Files in Python, write file in Python, write to file in Python, Delete a File in Python and remove folder in Python.

Related Articles:

Functions in Python with Examples

Loops in Python 3 with Examples

7 Python Operators with Examples

Python Introduction for Programmers [Part 1]

6 Python Conditional Statements with Examples

Inheritance in python with examples

Encapsulation and Polymorphism in Python with Examples

Python RegEx with Examples

Python Exception Handling with Examples

Python Datetime with Examples

Reference:

Python file handling official page

Shweta Mamidwar

I am Shweta Mamidwar working as a Intern in Product Company. Likes to share knowledge.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link
Powered by Social Snap