繁体   English   中英

试图删除文件但它不工作

[英]trying to delete file but its not working

我试图删除一个文件,但即使该文件存在,它也只会执行 else 语句。

我也尝试删除其他文件,但我得到了相同的结果。

这是代码:

def deletees():
    if os.path.exists("C:\X-Folder\plugins\autorun"):
        shutil.rmtree("C:\X-Folder\plugins\autorun")
    else:
        print("error: does not exists")

deletees()

如果您尝试删除单个文件:

os.remove(r"C:\X-Folder\plugins\autorun")
# or 
os.remove("C:\\X-Folder\\plugins\\autorun")

如果您尝试删除目录或目录树:

shutil.rmtree(r"C:\X-Folder\plugins\autorun")
# or 
shutil.rmtree("C:\\X-Folder\\plugins\\autorun")

请注意,使用了原始( r )字符串,因此\字符不会被转义。

因此,您的具体示例如下所示:

  • 取消注释最适合您的情况的行。
def deletees():
    if os.path.exists("C:\\X-Folder\\plugins\\autorun"):
        shutil.rmtree("C:\\X-Folder\\plugins\\autorun")  # uncomment me for a directory
        # os.remove("C:\\X-Folder\\plugins\\autorun")      # uncomment me for a file
    else:
        print("error: does not exists")
deletees()

最后还有os.rmdiros.removedirs但它们只适用于空目录,我不建议使用它们中的任何一个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM