如何删除文件或文件夹?
当前回答
在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中删除文件或文件夹?
对于Python 3,要单独删除文件和目录,请分别使用unlink和rmdir Path对象方法:
from pathlib import Path
dir_path = Path.home() / 'directory'
file_path = dir_path / 'file'
file_path.unlink() # remove file
dir_path.rmdir() # remove directory
请注意,您也可以对Path对象使用相对路径,并且可以使用Path.cwd检查当前工作目录。
有关在Python 2中删除单个文件和目录的信息,请参阅下面标记的部分。
要删除包含内容的目录,请使用shutil.rmtree,并注意这在Python 2和3中可用:
from shutil import rmtree
rmtree(dir_path)
集会示威
Python 3.4中的新功能是Path对象。
让我们使用一个来创建一个目录和文件来演示用法。请注意,我们使用/来连接路径的部分,这可以解决操作系统之间的问题以及在Windows上使用反斜杠的问题(您需要将反斜杠加倍,如\\或使用原始字符串,如r“foo\bar”):
from pathlib import Path
# .home() is new in 3.5, otherwise use os.path.expanduser('~')
directory_path = Path.home() / 'directory'
directory_path.mkdir()
file_path = directory_path / 'file'
file_path.touch()
现在:
>>> file_path.is_file()
True
现在让我们删除它们。首先文件:
>>> file_path.unlink() # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
我们可以使用globbing删除多个文件-首先让我们为此创建几个文件:
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
然后只需遍历glob模式:
>>> for each_file_path in directory_path.glob('*.my'):
... print(f'removing {each_file_path}')
... each_file_path.unlink()
...
removing ~/directory/foo.my
removing ~/directory/bar.my
现在,演示如何删除目录:
>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
如果我们想删除目录和其中的所有内容呢?对于此用例,请使用shutil.rmtree
让我们重新创建目录和文件:
file_path.parent.mkdir()
file_path.touch()
注意,除非rmdir为空,否则它会失败,这就是为什么rmtree如此方便的原因:
>>> directory_path.rmdir()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "~/anaconda3/lib/python3.6/pathlib.py", line 1270, in rmdir
self._accessor.rmdir(self)
File "~/anaconda3/lib/python3.6/pathlib.py", line 387, in wrapped
return strfunc(str(pathobj), *args)
OSError: [Errno 39] Directory not empty: '/home/username/directory'
现在,导入rmtree并将目录传递给函数:
from shutil import rmtree
rmtree(directory_path) # remove everything
我们可以看到整个事情都被删除了:
>>> directory_path.exists()
False
Python 2
如果您使用的是Python 2,则有一个名为pathlib2的pathlib模块的后端,可以使用pip安装:
$ pip install pathlib2
然后可以将库别名为pathlib
import pathlib2 as pathlib
或者直接导入Path对象(如下所示):
from pathlib2 import Path
如果太多,可以使用os.remove或os.unlink删除文件
from os import unlink, remove
from os.path import join, expanduser
remove(join(expanduser('~'), 'directory/file'))
or
unlink(join(expanduser('~'), 'directory/file'))
并且可以使用os.rmdir删除目录:
from os import rmdir
rmdir(join(expanduser('~'), 'directory'))
注意,还有一个os.removedirs-它只递归地删除空目录,但可能适合您的用例。
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)
您可以使用内置的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()
下面是一个同时使用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))
在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()
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录