![](/img/trans.png)
[英]reading all the files in a directory with specific extension using glob 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.