如何删除文件或文件夹?
当前回答
如果您喜欢编写一段漂亮且可读的代码,我建议使用子流程:
import subprocess
subprocess.Popen("rm -r my_dir", shell=True)
如果你不是软件工程师,那么可以考虑使用Jupyter;您可以简单地键入bash命令:
!rm -r my_dir
传统上,您使用shutil:
import shutil
shutil.rmtree(my_dir)
其他回答
用于删除文件的Python语法
import os
os.remove("/tmp/<file_name>.txt")
or
import os
os.unlink("/tmp/<file_name>.txt")
or
用于Python的pathlib库版本>=3.4
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))
这是我删除目录的功能。“路径”需要完整的路径名。
import os
def rm_dir(path):
cwd = os.getcwd()
if not os.path.exists(os.path.join(cwd, path)):
return False
os.chdir(os.path.join(cwd, path))
for file in os.listdir():
print("file = " + file)
os.remove(file)
print(cwd)
os.chdir(cwd)
os.rmdir(os.path.join(cwd, path))
下面是一个同时使用os.remove和shutil.rmtree的健壮函数:
def remove(path):
""" param <path> could either be relative or absolute. """
if os.path.isfile(path) or os.path.islink(path):
os.remove(path) # remove the file
elif os.path.isdir(path):
shutil.rmtree(path) # remove dir and all contains
else:
raise ValueError("file {} is not a file or dir.".format(path))
import os
folder = '/Path/to/yourDir/'
fileList = os.listdir(folder)
for f in fileList:
filePath = folder + '/'+f
if os.path.isfile(filePath):
os.remove(filePath)
elif os.path.isdir(filePath):
newFileList = os.listdir(filePath)
for f1 in newFileList:
insideFilePath = filePath + '/' + f1
if os.path.isfile(insideFilePath):
os.remove(insideFilePath)
对于删除文件:
os.unlink(path, *, dir_fd=None)
or
os.remove(path, *, dir_fd=None)
这两个函数在语义上是相同的。此函数用于删除文件路径。若路径不是文件,而是目录,则引发异常。
删除文件夹:
shutil.rmtree(path, ignore_errors=False, onerror=None)
or
os.rmdir(path, *, dir_fd=None)
为了删除整个目录树,可以使用shutil.rmtree()。os.rmdir仅在目录为空且存在时有效。
对于向父级递归删除文件夹:
os.removedirs(name)
它使用self删除每个空的父目录,直到父目录包含一些内容
例如,如果目录为空,os.removedirs('abc/xyz/pqr')将按“abc/xyz/pqr”、“abc/xy z”和“abc”的顺序删除目录。
有关更多信息,请查看官方文档:os.unlink、os.remove、os.rmdir、shutil.rmtree、os.removedirs