허치슨 전
지정된 폴더에 파이썬 삭제 파일은 일반적으로 사용되는 기능입니다. 나는 우리가 선택의 여지가 없었다하지만 더 실용적인의 템플릿을 이동하기 위해, 많은 장소는 적절한 템플릿을 찾을 수 없습니다 찾을 수 있습니다.
기본 모듈
은 listDir 일반적인 사용 : 이것은 여러 모듈 내부에 사용되는 디렉토리에있는 모든 파일의 함수이다 :
import os
filenames = os.listdir('.')
print(filenames)
또 다른 디렉토리의 특정 파일이 있는지 확인하는 것입니다, 이것은 특정 사용은 다음과됩니다 name.swith () 함수입니다 :
state = any(name.endswith('.py') for name in filenames)
print(state)
하나는 디렉토리에 서브 디렉토리를 찾을 수 있습니다. 으로는 다음과 서브 디렉토리의 정적에있는 모든 파일을 다음과 같이 :
tmp_path = os.path.join(BASE_PATH,'static/')
또 다른 방법은 해당 디렉토리의 특정 파일을 찾는 데 사용. 글롭 모듈은 일반적으로 사용된다. 글로브 모듈은 내용이 매우 작고, 간단한 모듈 중 하나입니다. 특정 규칙에 맞춰 파일 경로 이름을 찾기 위해 사용합니다. 특정 방법의 사용은 다음과 같습니다 :
fileNames = glob.glob(path + r'/*')
분석 예
다음 예제가 표시됩니다 : 특정 분석 및 운영 결과는 매우 간단합니다, 당신은 작업을해야합니다;
'''
遇到问题没人解答?小编创建了一个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)