TCAX 字幕特效制作工具官方论坛 | ASS | TCAS | Python | Aegisub | Lua

 找回密码
 新人加入
查看: 4336|回复: 1
打印 上一主题 下一主题

[其他] Python 如何删除文件或文件夹? [复制链接]

Rank: 4

跳转到指定楼层
楼主
发表于 2021-8-19 08:24:37 |只看该作者 |倒序浏览
本帖最后由 Seekladoom 于 2021-8-19 08:42 编辑

来源链接:https://blog.csdn.net/cyan20115/article/details/106548995


在本教程中,我们将学习如何在Python删除文件或目录。 使用os模块,在Python中删除文件或文件夹的过程非常简单。
  • os.remove –删除文件。
  • os.rmdir –删除文件夹。
  • shutil.rmtree –删除目录及其所有内容。


1.删??除文件。
首先,我们将看到使用os.remove从目录中删除文件的方法
  1. #!/usr/bin/python
  2. import os

  3. # getting the filename from the user
  4. file_path = input("Enter filename:- ")

  5. # checking whether file exists or not
  6. if os.path.exists(file_path):
  7.     # removing the file using the os.remove() method
  8.     os.remove(file_path)
  9. else:
  10.     # file not found message
  11.     print("File not found in the directory")
复制代码
输出量
  1. Enter filename:- sample.txt
  2. File not found in the directory
复制代码
2.删除一个文件夹。
我们要删除的文件夹必须为空。 Python将显示警告说明文件夹不为空。 删除文件夹之前,请确保其为空。 我们可以使用os.listdir()方法获取目录中存在的文件列表。 由此,我们可以检查文件夹是否为空。

  1. #!/usr/bin/python
  2. import os

  3. # getting the folder path from the user
  4. folder_path = input("Enter folder path:- ")

  5. # checking whether folder exists or not
  6. if os.path.exists(folder_path):

  7.     # checking whether the folder is empty or not
  8.     if len(os.listdir(folder_path)) == 0:
  9.         # removing the file using the os.remove() method
  10.         os.rmdir(folder_path)
  11.     else:
  12.         # messaging saying folder not empty
  13.         print("Folder is not empty")
  14. else:
  15.     # file not found message
  16.     print("File not found in the directory")
复制代码
输出量
  1. Enter folder path:- sample
  2. Folder is not empty
复制代码
3.删除目录及其所有内容。
  1. #!/usr/bin/python
  2. import os
  3. import sys
  4. import shutil

  5. # Get directory name
  6. mydir= input("Enter directory name: ")

  7. try:
  8.     shutil.rmtree(mydir)
  9. except OSError as e:
  10.     print("Error: %s - %s." % (e.filename, e.strerror))
复制代码
输出量
  1. Enter directory name: d:\logs
  2. Error: d:\logs - The system cannot find the path specified.
复制代码
参考文献

Rank: 4

沙发
发表于 2021-8-19 08:31:46 |只看该作者
注:此贴主要目的是为了方便TCAX在自动化生成ASS特效字幕或TCAS特效字幕以后,删除TCAX生成的多余文件用的。

目前TCAX还无法通过调用OS库的方式来删除TCAX生成的多余文件。。。_(:з」∠)_
您需要登录后才可以回帖 登录 | 新人加入

GitHub|TCAX 主页

GMT+8, 2024-4-29 12:38

Powered by Discuz! X2

© 2001-2011 Comsenz Inc.

回顶部
RealH