如何删除文件或文件夹?

2024-04-27 04:26:05 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

使用

shutil.rmtree(path[, ignore_errors[, onerror]])

(请参阅有关shutil的完整文档)和/或

os.remove

以及

os.rmdir

(关于os的完整文档。)

^{}删除文件。

^{}删除空目录。

^{}删除目录及其所有内容。


Python 3.4+^{}模块中的^{}对象还公开了以下实例方法:

  • ^{}删除文件或符号链接。

  • ^{}删除空目录。

删除文件的Python语法

import os
os.remove("/tmp/<file_name>.txt")

或者

import os
os.unlink("/tmp/<file_name>.txt")

或者

pathlibPython版本库>;3.5

file_to_rem = pathlib.Path(“/tmp/<file_name>.txt”)
file_to_rem.unlink()

Path.unlink(缺少'u ok=False)

用于删除文件或符号链接的取消链接方法。

If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist.
If missing_ok is true, FileNotFoundError exceptions will be ignored (same behavior as the POSIX rm -f command).
Changed in version 3.8: The missing_ok parameter was added.

最佳实践

  1. 首先,检查文件或文件夹是否存在,然后仅删除该文件。这可以通过两种方式实现:
    a、 os.path.isfile("/path/to/file")
    b、 使用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:    ## Show an error ##
    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 failed, report it back to 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 tree; if failed show an error using try...except on screen
try:
    shutil.rmtree(mydir)
except OSError as e:
    print ("Error: %s - %s." % (e.filename, e.strerror))

相关问题 更多 >