python怎么删除文件,python删除文件的几种方法
很多时候开发者需要删除文件。可能是他错误地创建了文件,或者不再需要该文件。无论出于何种原因,都有一些方法可以通过Python来删除文件,而无需手动查找文件并通过UI交互来进行删除操作。
os.remove()删除文件 os.unlink()删除文件。它是remove()方法的Unix名称。 shutil.rmtree()删除目录及其下面所有内容。 pathlib.Path.unlink()在Python 3.4及更高版本中用来删除单个文件pathlib模块。
os.remove(path)
path —— 这是要删除的路径或文件名。
# Importing the os library import os # Inbuilt function to remove files os.remove("test_file.txt") print("File removed successfully")
File removed successfully
#importing the os Library import os #checking if file exist or not if(os.path.isfile("test.txt")): #os.remove() function to remove the file os.remove("demo.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
File Deleted successfully
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)
从os模块导入os模块和listdir。必须使用listdir才能获取特定文件夹中所有文件的列表,并且需要os模块才能删除文件。 my_path是包含所有文件的文件夹的路径。 我们正在遍历给定文件夹中的文件。listdir用于获取特定文件夹中所有文件的一个列表。 endswith用于检查文件是否以.txt扩展名结尾。当我们删除文件夹中的所有.txt文件时,如果条件可以验证,则进行此操作。 如果文件名以.txt扩展名结尾,我们将使用os.remove()函数删除该文件。此函数将文件的路径作为参数。my_path + file_name是我们要删除的文件的完整路径。
#Importing os and glob modules import os, glob #Loop Through the folder projects all files and deleting them one by one for file in glob.glob("pythonpool/*"): os.remove(file) print("Deleted " + str(file))
Deleted pythonpool\test1.txt Deleted pythonpool\test2.txt Deleted pythonpool\test3.txt Deleted pythonpool\test4.txt
Shutil.rmtree(path,ignore_errors = False,onerror = None)
# Python program to demonstrate 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)
#Example of file deletion by pathlib import pathlib rem_file = pathlib.Path("pythonpool/testfile.txt") rem_file.unlink()
本文地址:百科问答频道 https://www.neebe.cn/wenda/903433.html,易企推百科一个免费的知识分享平台,本站部分文章来网络分享,本着互联网分享的精神,如有涉及到您的权益,请联系我们删除,谢谢!