使用Python脚本删除文件

2 投票
2 回答
618 浏览
提问于 2025-04-15 14:21

我想用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')

撰写回答