如何删除文件或文件夹?
当前回答
在Python中删除文件或文件夹
Python中有多种删除文件的方法,但最好的方法如下:
os.remove()删除文件。os.unlink()删除文件。它是remove()方法的Unix名称。shutil.rmtree()删除目录及其所有内容。pathlib.Path.unlink()删除单个文件。pathlib模块在Python 3.4及更高版本中可用。
os.remove()
示例1:使用os.Remove()方法删除文件的基本示例。
import os
os.remove("test_file.txt")
print("File removed successfully")
示例2:使用os.path.isfile检查文件是否存在,并使用os.remove删除文件
import os
#checking if file exist or not
if(os.path.isfile("test.txt")):
#os.remove() function to remove the file
os.remove("test.txt")
#Printing the confirmation message of deletion
print("File Deleted successfully")
else:
print("File does not exist")
#Showing the message instead of throwig an error
示例3:Python程序删除具有特定扩展名的所有文件
import os
from os import listdir
my_path = 'C:\Python Pool\Test\'
for file_name in listdir(my_path):
if file_name.endswith('.txt'):
os.remove(my_path + file_name)
示例4:删除文件夹中所有文件的Python程序
要删除特定目录中的所有文件,只需使用*符号作为模式字符串。#导入os和glob模块导入os,glob#循环浏览文件夹项目所有文件并逐个删除它们对于glob.glob(“pythonpool/*”)中的文件:os.remove(文件)打印(“已删除”+str(文件))
os.unlink()
os.unlink()是os.remove()的别名或另一个名称。在Unix os中,remove也称为unlink。注意:os.unlink()和os.remove()的所有功能和语法都相同。它们都用于删除Python文件路径。这两个都是Python标准库中os模块中的方法,用于执行删除功能。
shutil.rmtree()
示例1:Python程序使用shutil.rmtree()删除文件
import shutil
import os
# location
location = "E:/Projects/PythonPool/"
# directory
dir = "Test"
# path
path = os.path.join(location, dir)
# removing directory
shutil.rmtree(path)
示例2:Python程序使用shutil.rmtree()删除文件
import shutil
import os
location = "E:/Projects/PythonPool/"
dir = "Test"
path = os.path.join(location, dir)
shutil.rmtree(path)
pathlib.Path.rmdir()以删除空目录
Pathlib模块提供了与文件交互的不同方式。Rmdir是允许您删除空文件夹的路径函数之一。首先,您需要为目录选择Path(),然后调用rmdir()方法将检查文件夹大小。如果它是空的,它将删除它。
这是删除空文件夹的好方法,而不用担心丢失实际数据。
from pathlib import Path
q = Path('foldername')
q.rmdir()
其他回答
用于删除文件的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))
为了避免Éric Araujo评论中强调的TOCTOU问题,您可以捕捉一个异常来调用正确的方法:
def remove_file_or_dir(path: str) -> None:
""" Remove a file or directory """
try:
shutil.rmtree(path)
except NotADirectoryError:
os.remove(path)
因为shutil.rmtree()将只删除目录,os.remove()或os.unlink()将仅删除文件。
如果您喜欢编写一段漂亮且可读的代码,我建议使用子流程:
import subprocess
subprocess.Popen("rm -r my_dir", shell=True)
如果你不是软件工程师,那么可以考虑使用Jupyter;您可以简单地键入bash命令:
!rm -r my_dir
传统上,您使用shutil:
import shutil
shutil.rmtree(my_dir)
删除文件夹中的所有文件
import os
import glob
files = glob.glob(os.path.join('path/to/folder/*'))
files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder
for file in files:
os.remove(file)
删除目录中的所有文件夹
from shutil import rmtree
import os
// os.path.join() # current working directory.
for dirct in os.listdir(os.path.join('path/to/folder')):
rmtree(os.path.join('path/to/folder',dirct))
您可以使用内置的pathlib模块(需要Python 3.4+,但PyPI上有旧版本的后端:pathlib、pathlib2)。
要删除文件,可以使用unlink方法:
import pathlib
path = pathlib.Path(name_of_file)
path.unlink()
或使用rmdir方法删除空文件夹:
import pathlib
path = pathlib.Path(name_of_folder)
path.rmdir()