如何在Python中删除早于5分钟的wav文件

2024-06-01 05:18:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我的烧瓶代码

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();

Tags: 文件pathimport文件夹appindexreturnrequest
1条回答
网友
1楼 · 发布于 2024-06-01 05:18:27

您可以使用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();

相关问题 更多 >