如何删除文件或文件夹?
原文由 Zygimantas 发布,翻译遵循 CC BY-SA 4.0 许可协议
import os
os.remove("/tmp/<file_name>.txt")
要么
import os
os.unlink("/tmp/<file_name>.txt")
要么
Python 版本的 pathlib 库 >= 3.4
file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()
Unlink 方法用于删除文件或符号链接。
- 如果 missing_ok 为 false(默认值),则在路径不存在时引发 FileNotFoundError。
- 如果 missing_ok 为真,则 FileNotFoundError 异常将被忽略(与 POSIX rm -f 命令的行为相同)。
- 在 3.8 版更改:添加了 missing_ok 参数。
首先,检查文件或文件夹是否存在,然后将其删除。您可以通过两种方式实现这一目标:
os.path.isfile("/path/to/file")
exception handling.
示例 os.path.isfile
#!/usr/bin/python
import os
myfile = "/tmp/foo.txt"
# If file exists, delete it.
if os.path.isfile(myfile):
os.remove(myfile)
else:
# If it fails, inform the user.
print("Error: %s file not found" % myfile)
#!/usr/bin/python
import os
# Get input.
myfile = raw_input("Enter file name to delete: ")
# Try to delete the file.
try:
os.remove(myfile)
except OSError as e:
# If it fails, inform the user.
print("Error: %s - %s." % (e.filename, e.strerror))
输入要删除的文件名:demo.txt
错误:demo.txt - 没有这样的文件或目录。
输入要删除的文件名:rrr.txt
错误:rrr.txt - 不允许操作。
输入要删除的文件名:foo.txt
shutil.rmtree()
示例 shutil.rmtree()
#!/usr/bin/python
import os
import sys
import shutil
# Get directory name
mydir = raw_input("Enter directory name: ")
# Try to remove the tree; if it fails, throw an error using try...except.
try:
shutil.rmtree(mydir)
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))
原文由 Anand Tripathi 发布,翻译遵循 CC BY-SA 4.0 许可协议
4 回答4.4k 阅读✓ 已解决
1 回答3.1k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
1 回答4.4k 阅读✓ 已解决
1 回答3.9k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
os.remove()
删除文件。os.rmdir()
删除一个空目录。shutil.rmtree()
删除目录及其所有内容。Path
Python 3.4+ 中的对象pathlib
模块还公开了这些实例方法:pathlib.Path.unlink()
删除文件或符号链接。pathlib.Path.rmdir()
删除一个空目录。