Files and folders python method to delete the specified folder

Hutchison ago

python delete files in the specified folder, is a commonly used functions. I find a lot of places, has not found a suitable template, we had no choice but to shift the template of a more practical.

The basic module

This will be used inside several modules, is a function of all the files in the directory: listdir common use:

import os

filenames = os.listdir('.')
print(filenames)

Another is to see if there are specific files in the directory, this is name.swith () function, the specific use is as follows:

state = any(name.endswith('.py') for name in filenames)
print(state)

One is to find subdirectories under that directory. As follows: All files in the subdirectories static as follows:

tmp_path = os.path.join(BASE_PATH,'static/')

Another method used to find a specific file in that directory. The glob module is generally used. glob module is one of the simplest module, the content is very small. Use it to find the file path name in line with specific rules. Use of specific methods are as follows:

fileNames = glob.glob(path + r'/*')

Analysis examples

There is shown in the following example: specific analytical and operational results are very simple, you need the operation;

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import os
import sys
import glob

def del_files(path):
    fileNames = glob.glob(path + r'/*')

    for fileName in fileNames:
        try:
            os.remove(fileName)
            print("remove file:%s" % fileNames)
        except:

except:
    try:
        os.mkdir(fileName)
        print("mkdir file:%s " % fileName)
    except:
        print("del file:%s " % fileName)
        del_files(fileName)
        os.rmdir(fileName)


def del_file(path):
lsdir = os.listdir(path)
print(lsdir)
if any(name.endswith('.py') for name in lsdir):
print("no txt in this dir")
else:
print("have txt and need to remove")

for file in lsdir:
try:
    c_path = os.path.join(path,file)
    os.remove(c_path)
    print("rm c path: %s " % c_path)
except:
    del_file(path)
    os.rmdir(file)
    print("rm failed try again: %s " % c_path)


if __name__ == '__main__':
BASE_PATH = os.getcwd()
print("below is base path:\n %s" % BASE_PATH)
tmp_path = os.path.join(BASE_PATH,'static/')
print("below is tmp_path:\n %s" % tmp_path)
#del_files(tmp_path)
del_file(tmp_path)
Published 706 original articles · won praise 829 · Views 1.32 million +

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/105125441