簡體   English   中英

在Windows上按Python類型刪除文件

[英]Deleting files by type in Python on Windows

我知道如何刪除單個文件,但是我在如何刪除一個類型的目錄中的所有文件的實現中丟失了。

說目錄是\\ myfolder

我想刪除所有.config文件的文件,但沒有刪除其他文件。 我該怎么做?

謝謝你

使用glob模塊:

import os
from glob import glob

for f in glob ('myfolder/*.config'):
   os.unlink (f)

我會做類似以下的事情:

import os
files = os.listdir("myfolder")
for f in files:
  if not os.path.isdir(f) and ".config" in f:
    os.remove(f)

它列出了目錄中的文件,如果它不是目錄,文件名中包含“.config”,則將其刪除。 您需要與myfolder位於同一目錄中,或者為其提供目錄的完整路徑。 如果你需要遞歸地執行此操作,我將使用os.walk 函數

你走了:

import os

# Return all files in dir, and all its subdirectories, ending in pattern
def gen_files(dir, pattern):
   for dirname, subdirs, files in os.walk(dir):
      for f in files:
         if f.endswith(pattern):
            yield os.path.join(dirname, f)


# Remove all files in the current dir matching *.config
for f in gen_files('.', '.config'):
   os.remove(f)

還要注意gen_files可以很容易地重寫以接受一個模式元組,因為str.endswith接受一個元組

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM