Deleting all files in a directory with Python

2019-01-16 02:40发布

I want to delete all files with the extension .bak in a directory. How can I do that in Python?

6条回答
可以哭但决不认输i
2楼-- · 2019-01-16 03:01

Use os.chdir to change directory . Use glob.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 and os.remove are synonyms for the same function.)

#!/usr/bin/env python
import glob
import os
directory='/path/to/dir'
os.chdir(directory)
files=glob.glob('*.bak')
for filename in files:
    os.unlink(filename)
查看更多
成全新的幸福
3楼-- · 2019-01-16 03:02

On Linux and macOS you can run simple command to the shell:

subprocess.run('rm /tmp/*.bak', shell=True)
查看更多
我想做一个坏孩纸
4楼-- · 2019-01-16 03:07

First glob them, then unlink.

查看更多
一夜七次
5楼-- · 2019-01-16 03:09

In Python 3.5, os.scandir is better if you need to check for file attributes or type - see os.DirEntry for properties of the object that's returned by the function.

import os 

for file in os.scandir(path):
    if file.name.endswith(".bak"):
        os.unlink(file.path)

This also doesn't require changing directories since each DirEntry already includes the full path to the file.

查看更多
再贱就再见
6楼-- · 2019-01-16 03:12

you can create a function. Add maxdepth as you like for traversing subdirectories.

def findNremove(path,pattern,maxdepth=1):
    cpath=path.count(os.sep)
    for r,d,f in os.walk(path):
        if r.count(os.sep) - cpath <maxdepth:
            for files in f:
                if files.endswith(pattern):
                    try:
                        print "Removing %s" % (os.path.join(r,files))
                        #os.remove(os.path.join(r,files))
                    except Exception,e:
                        print e
                    else:
                        print "%s removed" % (os.path.join(r,files))

path=os.path.join("/home","dir1","dir2")
findNremove(path,".bak")
查看更多
再贱就再见
7楼-- · 2019-01-16 03:13

Via os.listdir and os.remove:

import os

filelist = [ f for f in os.listdir(mydir) if f.endswith(".bak") ]
for f in filelist:
    os.remove(os.path.join(mydir, f))

Or via glob.glob:

import glob, os, os.path

filelist = glob.glob(os.path.join(mydir, "*.bak"))
for f in filelist:
    os.remove(f)

Be sure to be in the correct directory, eventually using os.chdir.

查看更多
登录 后发表回答