在Python中使用*删除特定扩展名的文件

在Python中使用*删除特定扩展名的文件,python,file,delete-file,Python,File,Delete File,我有两个文本文件名为: 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的正确方法是什么?对于您的问题,您可以看看内置函数的方法。只需检

我有两个文本文件名为:

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()
>>> name = "temp1.txt"
>>> name.startswith("temp") and name.endswith("txt")
True
然后,您可以将
for
循环用于
os.remove()


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

这回答了你的问题吗?我们是否可以通过
os.remove()
来实现这一点?是的
os.remove(文件名)
在这里也可以使用。
文件名
是一个
路径
对象
Path.unlink()?
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")