我有几个命名为以下的文本文件:
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()
os.remove()
来做到这一点? - Bogotaos.remove(filename)
在这里也可以使用。filename
是一个 Path
对象。
Path.unlink()
和 os.unlink(pathname)
一样,与 os.remove(pathname)
相同。 - Dr. CuriosityPath(".").glob("temp*.txt")
? - Bogotaimport 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)
关于您的问题,您可以查看内置函数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()
创建列表。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")