programing

Python을 사용하여 디렉토리의 모든 파일 삭제

cafebook 2023. 7. 2. 20:57
반응형

Python을 사용하여 디렉토리의 모든 파일 삭제

확장자가 있는 모든 파일을 삭제합니다..bak명부에파이썬에서 어떻게 해야 합니까?

경유 및 :

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))

단일 루프만 사용:

for f in os.listdir(mydir):
    if not f.endswith(".bak"):
        continue
    os.remove(os.path.join(mydir, f))

또는 경유:

import glob, os, os.path

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

를 사용하여 올바른 디렉토리에 있는지 확인합니다.

Python 3.5에서는 파일 속성이나 유형을 확인해야 하는 경우가 더 좋습니다. 함수에서 반환되는 개체 속성은 를 참조하십시오.

import os 

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

이는 또한 각각의 디렉토리를 변경할 필요가 없습니다.DirEntry파일의 전체 경로가 이미 포함되어 있습니다.

사용하다os.chdir디렉토리를 변경합니다.사용하다glob.glob'.bak'으로 끝나는 파일 이름 목록을 생성합니다.목록의 요소는 문자열일 뿐입니다.

그러면 당신은 사용할 수 있습니다.os.unlink파일을 제거합니다. (PS)os.unlink그리고.os.remove같은 함수에 대한 동의어입니다.)

#!/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)

함수를 만들 수 있습니다.하위 디렉터리를 이동하는 데 필요한 최대 깊이를 추가합니다.

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")

먼저 글로벌화한 다음 링크를 해제합니다.

저는 이것이 오래된 것이라는 것을 알고 있습니다. 하지만 여기 OS 모듈만 사용하여 그렇게 하는 방법이 있습니다.

def purgedir(parent):
    for root, dirs, files in os.walk(parent):                                      
        for item in files:
            # Delete subordinate files                                                 
            filespec = os.path.join(root, item)
            if filespec.endswith('.bak'):
                os.unlink(filespec)
        for item in dirs:
            # Recursively perform this operation for subordinate directories   
            purgedir(os.path.join(root, item))

한 줄 솔루션의 경우(둘 다)Windows그리고.Linux) ;

import glob,os

for file in glob.glob("<your_path>/*.bak"): print(file," these will be deleted")

if input("continue ?") == "Y":
    for file in glob.glob("<your_path>/*.bak"): os.remove(file)

Linux 및 macOS에서 셸에 대한 간단한 명령을 실행할 수 있습니다.

subprocess.run('rm /tmp/*.bak', shell=True)

언급URL : https://stackoverflow.com/questions/1995373/deleting-all-files-in-a-directory-with-python

반응형