Skip to main content
 首页 » 编程设计

python之在 Mac 上是否有与 Python 的 os.remove() 等效的功能

2025年05月04日11tuyile006

目前我有一些代码删除了我的程序创建的一些临时文件:

# Delete the generated files 
exts = [".lsys", ".py", ".pyc"] 
for ext in exts: 
    os.remove("{0}{1}{2}".format(self.grammarDir, filename, ext)) 

现在我正在尝试将应用程序移植到 Mac。看着 documentation对于 Python 2.7,它特别说明:

Remove (delete) the file path. If path is a directory, OSError is raised; see rmdir() below to remove a directory. This is identical to the unlink() function documented below. On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.

Availability: Unix, Windows. 

对于 Mac 是否有等同于 os.remove() 的方法,或者我是否一直在使用类似的方法?

os.system("rm {0}{1}{2}".format(self.grammarDir, filename, ext)) 

我需要与 Mac 的兼容性,保持与 Ubuntu 的兼容性将是一个巨大的好处(但并非绝对必要)。

编辑:

好吧,现在我觉得自己很傻。原来我在这段代码之上有一个中断的调用,所以没有到达删除代码。误诊了我的错误所在,以为它正在无声地失败。

请您参考如下方法:

Mac OS X 也是一个 Unix。从顶部链接documentation :

If not separately noted, all functions that claim “Availability: Unix” are supported on Mac OS X, which builds on a Unix core.