Deleting files with python scripts

I want to delete some files using python scripts (when using windows). I've tried the following code:

>>>import os
>>> os.remove ('D:\new.docx')

      

but I am getting the following error:

Traceback (most recent call last):

  File "<pyshell#1>", line 1, in -toplevel-

    os.remove ('D:\new.docx')
OSError: [Errno 22] Invalid argument: 'D:\new.docx'

      

Can anyone here help me with this?

THANKS.

Gilani

+2


source to share


2 answers


Several variants:

Escape backslash

:

>>> os.remove('D:\\new.docx')

      

The Windows Runtime Library accepts forward slash

as delimiter:



>>> os.remove('D:/new.docx')

      

Raw string :

>>> os.remove(r'D:\new.docx')

      

+6


source


\

is an escape char for python. try replacing it with \\

.

Example:



os.remove ('D:\\new.docx')

      

+6


source







All Articles