【问题标题】:Error when deleting a file in use with python删除与python一起使用的文件时出错
【发布时间】:2021-03-22 00:54:19
【问题描述】:

我正在创建一个脚本,它使用 Youtube API 将视频加载到文件夹中,然后将其删除。虽然视频已经加载,但 Python 不允许您删除该文件。它给了我错误:

WindowsError: [错误 32] 进程无法访问该文件,因为它正被另一个进程使用。

然后我尝试使用os.close(filevar),但是它返回了这个错误:

TypeError:需要一个整数(类型为 str)

我尝试过这样的事情来使变量成为整数,但它不起作用:

newest_file = 1 #Set the value of var in int
os.close(newest_file)   #Close process
newest_file = max(mp4_files, key = os.path.getctime) #Rewrite the var   
os.remove(newest_file)  #Remove the last video

我该如何解决这个问题?

【问题讨论】:

  • 文件是由您的代码还是由其他东西打开的?这不是真正的 Python 问题,更像是 Windows 问题。
  • 是的,文件是在我的代码中打开的
  • 如何打开文件?文件描述符(你需要的int值)应该从os.open返回。
  • 欢迎来到 Stackoverflow!请花时间吸收SO's recommendations 发给新用户的内容。您可以拨打tour;然后阅读what's on-topic here 并提供minimal reproducible example

标签: python api youtube-api


【解决方案1】:

我也遇到过这个问题,最近在windows中使用os.remove时出现了这个问题。 我使用 send2trash 库解决了它,而不是删除文件,文件将其发送到垃圾箱。

send2trash.send2trash(newest_file)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多