bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Python/Files, Modules, and the Standard Library
Python•Files, Modules, and the Standard Library

Python Delete File

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Python Delete File?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

os.___("demofile.txt")
3Order

Put the learning moves in the order that makes the concept easiest to apply.

To avoid getting an error, you might want to check if the file exists before you try to delete it:
Remove the file "demofile.
To delete a file, you must import the OS module, and run its os.

Delete a File

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

Example

Remove the file "demofile.txt":

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

Check if File exist

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

Example

Check if file exists, then delete it:

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

Delete Folder

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

Example

Remove the folder "myfolder":

import os
os.rmdir("myfolder")

Note

You can only remove empty folders.

Previous

How to Add Two Numbers in Python

Next

Python statistics Module