我有几个文本文件,命名为
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()
对于你的问题,你可以看一下内置函数的方法。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()
来创建列表。
这种模式匹配可以通过使用 水珠 模块。如果你不想使用 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")