Python - 如何在 Ubuntu 的根文件夹中打开或创建文件?
Python - How to open or create a file in root folder on Ubuntu?
我想创建(或打开如果存在的话)一个 python 的文件,路径为 /etc/yate/input.txt。这是我的代码:
try:
file = open("input.txt", "wb")
except IOError:
print "Error"
with file:
doSomething()
我收到 "Error" 消息
我该如何解决?
您可以在 open()
中提供完整路径,而不仅仅是文件名:
file = open("/etc/yate/input.txt", "wb")
完整代码:
try:
file = open("/etc/yate/input.txt", "wb")
except IOError:
print "Error"
else:
dosomething()
finally:
file.close()
但是,由于 with
用作上下文管理器,您可以使用 with
的强大功能使您的代码更短。
代码:
try:
with open("input.txt", "wb") as file:
dosomething()
except IOError:
print "Error"
您可以导入os.path,然后检查文件是否存在。这可能也已经在这里回答过 How do I check whether a file exists using Python?
代码:
import os.path
现在,检查您的文件路径中是否存在该文件名:
file_exists = os.path.isfile(/etc/yate/input.txt)
if file_exists:
do_something
或者,如果您想执行某些操作,例如创建并打开不存在的文件:
if not file_exists:
do_something_else
更新:
在我提供的 link 中,还有其他方法可以做到这一点,比如使用 pathlib 而不是 os.path。
我想创建(或打开如果存在的话)一个 python 的文件,路径为 /etc/yate/input.txt。这是我的代码:
try:
file = open("input.txt", "wb")
except IOError:
print "Error"
with file:
doSomething()
我收到 "Error" 消息
我该如何解决?
您可以在 open()
中提供完整路径,而不仅仅是文件名:
file = open("/etc/yate/input.txt", "wb")
完整代码:
try:
file = open("/etc/yate/input.txt", "wb")
except IOError:
print "Error"
else:
dosomething()
finally:
file.close()
但是,由于 with
用作上下文管理器,您可以使用 with
的强大功能使您的代码更短。
代码:
try:
with open("input.txt", "wb") as file:
dosomething()
except IOError:
print "Error"
您可以导入os.path,然后检查文件是否存在。这可能也已经在这里回答过 How do I check whether a file exists using Python?
代码:
import os.path
现在,检查您的文件路径中是否存在该文件名:
file_exists = os.path.isfile(/etc/yate/input.txt)
if file_exists:
do_something
或者,如果您想执行某些操作,例如创建并打开不存在的文件:
if not file_exists:
do_something_else
更新: 在我提供的 link 中,还有其他方法可以做到这一点,比如使用 pathlib 而不是 os.path。