Python Add, Remove, Edit File or Folder (File Handling )

Python is a great language when it comes to writing limited syntax. File Handling is one of the topics in python which lets programmers create, read and delete files from the directory. To perform file system operations in python, the programmer has to import the os library and use the below-given syntax to perform file system operations are:-

w  write mode
r  read mode
a  append mode

w+  create file if it doesn't exist and open it in (over)write mode
r+  open an existing file in read+write mode
a+  create file if it doesn't exist and open it in append mode
    

Create a File using Python

In the below example, we’ll be creating a file in OS.

import os

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

This code will create a file by the name “demofile.txt” in the home location.

Create a File at a specific location using Python

In the below example, we’ll be creating a file in OS at a specific location.

import os

f = open("Desktop/demofile.txt", "a")

This code will create a file by the name “demofile.txt” on the Desktop.

Create a File at a specific location and add text using Python

In the below example, we’ll be creating a file in OS at a specific location and add “This is an example text for BasicCodist Python Beginners tutorial” to the file.

import os

f = open("Desktop/demofile.txt", "a")
f.write("This is an example text for BasicCodist Python Beginners tutorial")
f.close()

This code will create a file by the name “demofile.txt” in the Desktop with the text “This code will create a file by the name “demofile.txt” in the Desktop.”.

Advertisements

Read from demofile.txt using Python

In the below example, we’ll be reading the text we just saved in the demofile.txt

import os

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

This code will print the text saved in filedemo.txt

Remove demofile.txt using Python

In the below example, we delete the demofile.txt

import os

os.remove("Desktop/demofile.txt")

This will remove/delete demofile.txt saved on the Desktop.

Advertisements

Conclusion

File Handling in python can be used to store or access information while creating windows applications or performing any operation. While storing information, you can use Dictionary to be more organized. One of the examples of using File Handling is in Data Visualisation where you can store or read data to visualize data.

Written by

XR Developer responsible for end-to-end development of XR solutions spanning multiple domains, by using various XR and WebXR libraries.

1 thought on “Python Add, Remove, Edit File or Folder (File Handling )

Leave a Reply