使用Python脚本删除文件
我想用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'
这里有人能帮我解决这个问题吗?
谢谢。
Gillani
2 个回答
6
\
在 Python 中是一个转义字符。你可以试着把它换成 \\
。
例如:
os.remove ('D:\\new.docx')
6
这里有几个选择:
可以对反斜杠
进行转义:
>>> os.remove('D:\\new.docx')
在Windows的运行时库中,可以使用正斜杠
作为分隔符:
>>> os.remove('D:/new.docx')
>>> os.remove(r'D:\new.docx')