Python Glossary Русский

all Python 3osfunction

os.remove

os — removal

Delete a file; directories need os.rmdir() (or shutil.rmtree() for a non-empty tree). Exact synonym of os.unlink().

Syntax

os.remove(path)

On a directory it raises — IsADirectoryError on Linux, PermissionError or OSError elsewhere. On Windows a file held open by another process cannot be removed and you get PermissionError; on Unix the removal succeeds and the space is freed once the file is closed. If the file may be absent, catch FileNotFoundError instead of checking exists first: the file can vanish between the check and the call.

Examples

import os
open('temp.txt', 'w').close()
os.remove('temp.txt')
print(os.path.exists('temp.txt'))   # → False
try:
    os.remove('temp.txt')   # файла уже нет
except FileNotFoundError:
    print('файла нет')   # → файла нет — ловим исключение, а не проверяем exists заранее

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy