DELETE FILES



Python - Delete Files


Delete a File :


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

OS module in Python provides functions for interacting with the operating system. os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method


import os
os.remove("freedomfile2.py")

## As a result, file gets removed from the place it stored.

Check if File exist :


To avoid getting an error, you might want to check if the file exists before you try to delete it:


import os
if os.path.exists("freedomfile3.py"):
 os.remove("freedomfile3.py")
else:
  print("the file does not exist")

## as a result the file gets deleted, if the file exists.


## Now after file got deleted,check out the result with the same program.

import os
if os.path.exists("freedomfile3.py"):
 os.remove("freedomfile3.py")
else:
  print("the file does not exist")


======o/p========

the file does not exist



Delete Folder :


To delete an entire folder, use the os.rmdir() method:


Remove the folder "python tutorial":

import os
os.rmdir("python tutorial")

## AS A RESULT FOLDER GETS DELETED

Note: You can only remove empty folders.



RegEx SETS

Python - RegEx SETS

posted on 2019-11-12 23:06:24 - Python Tutorials


RegEx_Functions

Python - RegEx_Functions

posted on 2019-11-09 06:07:29 - Python Tutorials


RegEx_Sets

Python - RegEx_Sets

posted on 2019-11-09 05:30:54 - Python Tutorials


Prompt Examples

ChatGPT Prompt Examples

posted on 2023-06-21 22:37:19 - ChatGPT Tutorials


Use Cases

Chat GPT Key Use Cases

posted on 2023-06-21 21:03:17 - ChatGPT Tutorials


Prompt Frameworks

Prompt Frameworks

posted on 2023-06-21 19:33:06 - ChatGPT Tutorials