【问题标题】:Creating a file if it doesn't exists, then opening the file in RW mode如果文件不存在则创建文件,然后以 RW 模式打开文件
【发布时间】:2017-10-10 19:09:06
【问题描述】:

在 Python 中,如果文件不存在,我会尝试创建一个文件,然后以读/写模式打开它。我能够表达的最简洁的方式是:

with os.fdopen(os.open('foo.bar', os.O_RDWR | os.O_CREAT), "r+") as f:
    # read file contents...
    # append new stuff...

有没有更好的方法来做到这一点?我应该检查if not os.path.exists('foo.bar'),如果文件不存在则创建文件,然后以“r+”模式打开文件?

本质上:

 if not os.path.exists('foo.bar'):
      os.makedirs('foo.bar') # or open('foo.bar', 'a').close()
 with open('foo.bar', "r+") as f:
    # read file contents...
    # append new stuff...

【问题讨论】:

  • 总是添加通用的python标签,顺便说一句
  • @juanpa.arrivillaga 好点;欣赏它!
  • 嗯,你不能只使用'a+' 模式,如果它不存在,它将创建它,并将流定位在末尾?
  • @juanpa.arrivillaga 使用 f.seek(0),对吗?出于某种原因,我不喜欢它的样子,但我觉得我只是很奇怪哈哈。可能最好这样做
  • 但是您是否只是从文件中读取以便可以附加到它?

标签: python python-3.x file io


【解决方案1】:

主要问题是如果文件已经存在,你是否要截断它。

如果是这样,那么做:

with open("filename", "w+") as f:
  f.write("Hello, world")

否则,按照juanpa.arrivillaga 的建议:

with open("filename", "a+") as f
  f.write("Hello, world")

“a+”打开文件并从文件末尾开始。查看documentation 了解更多关于它是如何工作的。

【讨论】:

    【解决方案2】:

    第二个选项有点不确定,因为如果您的程序不是文件的唯一用户/消费者,那么在打开之前进行测试会使您面临竞争条件。

    我可能会使用 a+ 并回到开头

    with open("file", "a+") as f:
        f.seek(0)
        f.read()
        ...
    

    我猜要考虑的其他事情就是放弃 python 文件对象并直接使用 os。

    fd = os.open("file", os.O_RDWR | os.O_CREAT)
    buffer = os.read(fd)
    new_data = b'stuff to append'
    os.write(fd, new_data)
    os.close(fd)
    
    etc
    

    这将需要更多代码,因为您必须手动跟踪文件句柄,这可能比使用“with”上下文管理更痛苦。

    【讨论】:

      猜你喜欢
      • 2012-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-04
      • 1970-01-01
      • 2016-06-18
      • 1970-01-01
      相关资源
      最近更新 更多