![](/img/trans.png)
[英]How do you grab the root Windows directory of the computer running your code? (Python)
[英]How do you delete a file (located in the same directory that your script is running in) in Python?
我正在尝试删除运行Python程序所在目录中的某个文件。
def erase_custom_file():
directory=os.listdir(os.getcwd())
for somefile in directory:
if somefile=="file.csv":
os.remove(???)
我不确定下一步应该怎么做。 我知道os.remove
接受参数的路径,但是我不确定如何将其定向到我想要的文件中。 请帮帮我?
使用unlink()和path.join()
>>> try:
... os.unlink(os.path.join(os.getcwd(),'file.csv'))
... except OSError, e:
... print e #file does not exist or you don't have permission
这应该工作:
os.remove( os.path.join( directory, somefile ) )
如果要删除较早创建的暂存文件,则可以尝试使用临时文件。 这些将在垃圾回收期间自动删除。 参考: http : //docs.python.org/library/tempfile.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.