【问题标题】:How to delete wav files older than 5 minutes in Python如何在 Python 中删除超过 5 分钟的 wav 文件
【发布时间】:2021-06-12 22:39:02
【问题描述】:

我需要从文件夹中删除 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();

【问题讨论】:

    标签: python file flask operating-system


    【解决方案1】:

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

    【讨论】:

    • 我无法尝试这个。我今天会尝试并写下结果。谢谢。
    • 它给出“FileNotFoundError: [WinError 2] 系统找不到指定的文件:'27161.wav'”错误。我认为这是因为 wav 文件不在根文件夹中,它们在 ~/static 文件夹中。你知道怎么做吗?
    • 我解决了这个问题,但这次它不检查修改时间。它会删除所有 wav 文件。
    • 我将 5 更改为 300 并且它现在可以工作了。我认为这个数字是第二个?
    • 哎呀。基本上是5秒。你需要把它设置为 300,因为 5 分钟等于 300 秒
    猜你喜欢
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 2016-09-19
    • 2014-01-20
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多