Метод Unlink, используемый для удаления файла или ссылки symbolik.
Если missing_ok имеет значение false (по умолчанию), вызывается FileNotFoundError, если путь не существует.
Если значение missing_ok равно true, исключения FileNotFoundError будут проигнорированы (такое же поведение, как у команды POSIX rm -f).
Изменено в версии 3.8: добавлен параметр missing_ok.
Лучшие практики
Сначала проверьте, существует ли файл или папка, а затем удалите их. Добиться этого можно двумя способами:
os.path.isfile("/path/to/file")
Использование exception handling.
ПРИМЕР для 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))
Соответствующий вывод
Введите имя файла для удаления: demo.txt Ошибка: demo.txt - Такого файла или каталога нет.
Введите имя файла для удаления: rrr.txt Ошибка: rrr.txt - Операция не разрешена.
Введите имя файла для удаления: 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))
Вот надежная функция, которая использует оба os.remove и shutil.rmtree:
defremove(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))