【问题标题】:Python - How to open or create a file in root folder on Ubuntu?Python - 如何在 Ubuntu 的根文件夹中打开或创建文件?
【发布时间】:2017-09-28 00:42:27
【问题描述】:

我想创建(或打开如果存在)一个带有路径 /etc/yate/input.txt 的 python 文件。这是我的代码:

try:
     file = open("input.txt", "wb")
except IOError:
     print "Error"
with file:
     doSomething()

我收到“错误”消息

我该如何解决?

【问题讨论】:

  • 运行代码而不捕获异常。这是什么?

标签: python ubuntu io path file-exists


【解决方案1】:

你可以导入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

更新: 在我提供的链接中,还有其他方法可以做到这一点,比如使用 pathlib 而不是 os.path。

【讨论】:

    【解决方案2】:

    您可以在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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-10
      • 2015-03-13
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      • 1970-01-01
      • 2015-07-22
      • 2010-10-06
      相关资源
      最近更新 更多