如何在 Python 中删除超过 5 分钟的 wav 文件

How to delete wav files older than 5 minutes in Python

我需要从文件夹中删除 wav 文件。我可以列出文件,但我不知道如何删除它们。如果文件夹超过 5 分钟并且它是一个 wav 文件,则需要将其删除。我需要在烧瓶中完成。

我的flask代码

from flask import Flask, render_template, request
import inference
import os

app = Flask(__name__)
app.static_folder = 'static'

@app.route("/")
def home():
    return render_template("index.html")

@app.route("/sentez", methods = ["POST"])
def sentez():
    if request.method == "POST":
        list_of_files = os.listdir('static')
        print(list_of_files)
        metin = request.form["metin"]
        created_audio, file_path = inference.create_model(metin)
        return render_template("index.html", my_audio = created_audio, audio_path = file_path)
    return render_template("index.html")

if __name__ == "__main__":
    app.run();

您可以使用os.remove()函数

import time
# time.time() gives you the current time
# os.path.getmtime(path) give you the modified time for a file
for filename in list_of_files:
    if filename[-3:]!='wav':
        continue

    modified_time=os.path.getmtime(filename)
    if time.time()-modified_time > 300: #time in seconds
        os.remove(filename)

所以你的代码最终会像这样

from flask import Flask, render_template, request
import inference
import os

app = Flask(__name__)
app.static_folder = 'static'

@app.route("/")
def home():
    return render_template("index.html")

@app.route("/sentez", methods = ["POST"])
def sentez():
    if request.method == "POST":
        list_of_files = os.listdir('static')
        print(list_of_files)
        for filename in list_of_files:
            if filename[-3:]!='wav':
                continue
            modified_time=os.path.getmtime(filename)
            if time.time()-modified_time > 300: #time in seconds
                os.remove(filename)
        metin = request.form["metin"]
        created_audio, file_path = inference.create_model(metin)
        return render_template("index.html", my_audio = created_audio, audio_path = file_path)
    return render_template("index.html")

if __name__ == "__main__":
    app.run();