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

3

我有几个命名为以下的文本文件:

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正确地完成这个任务?


1
https://dev59.com/0HI_5IYBdhLWcg3wDOjW - Fu Hanxi
这个回答是否解决了您的问题?按模式删除多个文件 - Maurice Meyer
4个回答

7
from pathlib import Path

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

有没有办法可以通过 os.remove() 来做到这一点? - Bogota
是的。os.remove(filename) 在这里也可以使用。filename 是一个 Path 对象。 Path.unlink()os.unlink(pathname) 一样,与 os.remove(pathname) 相同。 - Dr. Curiosity
请问您能解释一下这个命令的作用吗:Path(".").glob("temp*.txt") - Bogota

1
这种模式匹配可以使用 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)

0

关于您的问题,您可以查看内置函数str的方法。只需检查文件名的开头和结尾,例如:

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

然后你可以使用 for 循环和 os.remove()

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接