如何在Python中删除文件或文件夹?
在Python中,我该如何删除一个文件或文件夹呢?
18 个回答
740
用Python语法删除文件
import os
os.remove("/tmp/<file_name>.txt")
或者
import os
os.unlink("/tmp/<file_name>.txt")
或者
file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()
Path.unlink(missing_ok=False)
这个unlink方法用来删除文件或者符号链接。
- 如果missing_ok是false(默认值),当路径不存在时会抛出FileNotFoundError错误。
- 如果missing_ok是true,FileNotFoundError错误会被忽略(这和POSIX的rm -f命令的行为一样)。
- 在3.8版本中进行了更改:添加了missing_ok参数。
最佳实践
首先,检查文件或文件夹是否存在,然后再删除它。你可以通过两种方式来做到这一点:
os.path.isfile("/path/to/file")
- 使用
异常处理
。
示例:使用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))
相应的输出
Enter file name to delete : demo.txt Error: demo.txt - No such file or directory. Enter file name to delete : rrr.txt Error: rrr.txt - Operation not permitted. Enter file name to delete : foo.txt
用Python语法删除文件夹
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))
4858
你可以使用以下方法:
pathlib.Path.unlink()
可以用来删除一个文件或者符号链接。pathlib.Path.rmdir()
可以用来删除一个空文件夹。shutil.rmtree()
可以用来删除一个文件夹及其里面的所有内容。
如果你使用的是Python 3.3或更早的版本,可以用这些方法代替pathlib
的方法:
os.remove()
用来删除一个文件。os.unlink()
用来删除一个符号链接。os.rmdir()
用来删除一个空文件夹。