开发者社区 问答 正文

文件不存在才能写入

你想像一个文件中写入数据,但是前提必须是这个文件在文件系统上不存在。 也就是不允许覆盖已存在的文件内容。

展开
收起
哦哦喔 2020-04-17 12:23:32 1132 分享 版权
1 条回答
写回答
取消 提交回答
  • 可以在 open() 函数中使用 x 模式来代替 w 模式的方法来解决这个问题。比如:
    
    >>> with open('somefile', 'wt') as f:
    ...     f.write('Hello\n')
    ...
    >>> with open('somefile', 'xt') as f:
    ...     f.write('Hello\n')
    ...
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    FileExistsError: [Errno 17] File exists: 'somefile'
    >>>
    如果文件是二进制的,使用 xb 来代替 xt
    
    2020-04-17 12:23:40
    赞同 展开评论
问答地址: