Python: Delete Specific Files in Folder
To remove specific files in a folder, you can use the os.remove() function from Python’s os module.
Here is an example code demonstrating how to remove a specified file from a folder.
import os
# 指定要删除的文件路径
file_path = "path/to/file.txt"
# 检查文件是否存在
if os.path.exists(file_path):
# 删除文件
os.remove(file_path)
print("文件删除成功")
else:
print("文件不存在")
In the code above, the first step is to specify the file path to be deleted. Then, the os.path.exists() function is used to check if the file exists. If the file exists, the os.remove() function is used to delete it. If the file does not exist, a message “File does not exist” is output.