python cookbook 学习笔记 第五章 文件与IO (5) 文件不存在才能写入

  • 文件不存在才能写入
  • 问题:
    • 想向一个文件中写入数据,但前提是这个文件不存在,也就是说不允许覆盖已经存在的文件。
  • 解决方案:
    • 可以在 open()函数中使用 x 模式来代替w模式的方法解决这个问题:
with open("somefile.txt", "xt") as f:

    f.write("Hello world!\n")
# FileExistsError: [Errno 17] File exists: 'somefile.txt'
  • 讨论: 这个小节演示了再写文件时通常会遇到的一个问题的完美解决方案(一不小心覆盖一个已存在的文件)。一个替代 方案就是先测试这个文件是否存在:
import os
if not os.path.exists("somefile.txt"):
    with open("somefile.txt", "wt") as f:
        f.write("hello world!\n")

else:
    print("File already exists!")
  • 用 x 模式更加简单,但是 Python 2是不支持的。

猜你喜欢

转载自blog.csdn.net/qq_43539055/article/details/84889095