簡體   English   中英

在 Python 中使用 * 刪除特定擴展名的文件

[英]Deleting files of specific extension using * in Python

我有幾個名為:

temp1.txt
temp2.txt
temp3.txt
temp4.txt
track.txt

我只想刪除以temp開頭並以.txt結尾的文件。 我嘗試使用os.remove("temp*.txt")但我收到錯誤:

The filename, directory name, or volume label syntax is incorrect: 'temp*.txt'

使用 python 3.7 的正確方法是什么?

from pathlib import Path

for filename in Path(".").glob("temp*.txt"):
    filename.unlink()

對於您的問題,您可以查看內置 function str的方法。 只需檢查文件名的開頭和結尾,如下所示:

>>> name = "temp1.txt"
>>> name.startswith("temp") and name.endswith("txt")
True

然后你可以使用os.remove()for循環:

for name in files_list:
    if name.startswith("temp") and name.endswith("txt"):
        os.remove(name)

使用os.listdir()str.split()創建列表。

這種模式匹配可以通過使用glob模塊來完成。 如果您不想使用 os.path 模塊,pathlib 是另一種選擇

import os 
import glob
path = os.path.join("/home", "mint", "Desktop", "test1") # If you want to manually specify path
print(os.path.abspath(os.path.dirname(__file__)))   # To get the path of current directory 
print(os.listdir(path)) # To verify the list of files present in the directory 
required_files = glob.glob(path+"/temp*.txt") # This gives all the files that matches the pattern
print("required_files are ", required_files)
results = [os.remove(x) for x in required_files]
print(results)
import glob


# get a recursive list of file paths that matches pattern  
fileList = glob.glob('temp*.txt', recursive=True)    
# iterate over the list of filepaths & remove each file. 

for filePath in fileList:
    try:
        os.remove(filePath)
    except OSError:
        print("Error while deleting file")

暫無
暫無

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

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