使用python脚本删除文件

时间:2009-09-16 10:12:00

标签: python file

我想用python脚本删除一些文件(使用Windows时)。我尝试了以下代码:

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

但是我收到以下错误:

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'

这里的任何人都可以帮我吗?

感谢。

吉拉尼

2 个答案:

答案 0 :(得分:6)

\是python的转义字符。尝试将其替换为\\

例如:

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

答案 1 :(得分:6)

一些选择:

逃离backslash

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

Windows中的运行时库接受forward slash作为分隔符:

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

Raw string

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