如何删除文件或文件夹?
当前回答
在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()
其他回答
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)
Use
shutil.rmtree(path[, ignore_errors[, onerror]])
(参见shutil的完整文档)和/或
os.remove
and
os.rmdir
(操作系统的完整文档)
删除文件夹中的所有文件
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))
下面是一个同时使用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))
os.remove()删除文件。os.rmdir()删除空目录。shutil.rmtree()删除目录及其所有内容。
Python 3.4+pathlib模块中的路径对象还公开了以下实例方法:
pathlib.Path.unlink()删除文件或符号链接。pathlib.Path.rmdir()删除空目录。
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象