I want to delete all files with the extension .bak
in a directory. How can I do that in Python?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Use
os.chdir
to change directory . Useglob.glob
to generate a list of file names which end it '.bak'. The elements of the list are just strings.Then you could use
os.unlink
to remove the files. (PS.os.unlink
andos.remove
are synonyms for the same function.)On Linux and macOS you can run simple command to the shell:
First glob them, then unlink.
In Python 3.5,
os.scandir
is better if you need to check for file attributes or type - seeos.DirEntry
for properties of the object that's returned by the function.This also doesn't require changing directories since each
DirEntry
already includes the full path to the file.you can create a function. Add maxdepth as you like for traversing subdirectories.
Via
os.listdir
andos.remove
:Or via
glob.glob
:Be sure to be in the correct directory, eventually using
os.chdir
.