如何确保文件存在或可以创建之前写入到Python? [英] How to make sure a file exists or can be created before writing to it in Python?

查看:134
本文介绍了如何确保文件存在或可以创建之前写入到Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个函数,我希望它能 touch 一个文件,以便我可以写入该文件。如果该文件不存在,我会得到一个错误。我怎么能这样说?

I'm writing a function and I want it to touch a file so that I can write to that file. If the file doesn't exist, I will get an error. How can I say that?

推荐答案

只要打开文件进行写入,如果不存在

Just open the file for writing and it will be created if it doesn't exist (assuming you have proper permission to write to that location).

f = open('some_file_that_might_not_exist.txt', 'w')
f.write(data)

您将得到 IOError 如果您无法打开文件进行写入。

You will get an IOError if you can't open the file for writing.

这篇关于如何确保文件存在或可以创建之前写入到Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆