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 fileelif os.path.isdir(path):shutil.rmtree(path) # remove dir and all containselse:raise ValueError("file {} is not a file or dir.".format(path))
#!/usr/bin/pythonimport 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/pythonimport 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.txtError: demo.txt - No such file or directory.
Enter file name to delete : rrr.txtError: rrr.txt - Operation not permitted.
Enter file name to delete : foo.txt
删除文件夹的Python语法
shutil.rmtree()
示例shutil.rmtree()
#!/usr/bin/pythonimport osimport sysimport shutil
# Get directory namemydir = 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
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)
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()
>>> for each_file_path in directory_path.glob('*.my'):... print(f'removing {each_file_path}')... each_file_path.unlink()...removing ~/directory/foo.myremoving ~/directory/bar.my
>>> directory_path.rmdir()Traceback (most recent call last):File "<stdin>", line 1, in <module>File "~/anaconda3/lib/python3.6/pathlib.py", line 1270, in rmdirself._accessor.rmdir(self)File "~/anaconda3/lib/python3.6/pathlib.py", line 387, in wrappedreturn strfunc(str(pathobj), *args)OSError: [Errno 39] Directory not empty: '/home/username/directory'
现在,导入rmtree并将目录传递给函数:
from shutil import rmtreermtree(directory_path) # remove everything
import osimport 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 folderfor file in files:os.remove(file)
删除目录中的所有文件夹
from shutil import rmtreeimport 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))
import os#checking if file exist or notif(os.path.isfile("test.txt")):#os.remove() function to remove the fileos.remove("test.txt")#Printing the confirmation message of deletionprint("File Deleted successfully")else:print("File does not exist")#Showing the message instead of throwig an error
示例3:删除具有特定扩展名的所有文件的Python程序
import osfrom os import listdirmy_path = 'C:\Python Pool\Test\'for file_name in listdir(my_path):if file_name.endswith('.txt'):os.remove(my_path + file_name)
import os
def rm_dir(path):cwd = os.getcwd()if not os.path.exists(os.path.join(cwd, path)):return Falseos.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))