zoukankan      html  css  js  c++  java
  • python 文件不存在时才能写入,读写模式xt

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

    可以在open() 函数中使用x 模式来代替w 模式的方法来解决这个问题。比如:

    >>> with open('somefile', 'wt') as f:
    ... f.write('Hello
    ')
    ...
    >>> with open('somefile', 'xt') as f:
    ... f.write('Hello
    ')
    ...
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    FileExistsError: [Errno 17] File exists: 'somefile'
    >>>
    

    先测试这个文件是否存在

    >>> import os
    >>> if not os.path.exists('somefile'):
    ... with open('somefile', 'wt') as f:
    ... f.write('Hello
    ')
    ... else:
    ... print('File already exists!')
    ...
    File already exists!
    >>>
    

    显而易见,使用x 文件模式更加简单。要注意的是x 模式是一个Python3 对open() 函数特有的扩展。在Python 的旧版本或者是Python 实现的底层C 函数库中都是没有这个模式的。

  • 相关阅读:
    android实现计时器(转)
    单例模式和静态类
    ADC电阻分压采集相关知识
    什么是中断?
    什么是时钟芯片 ?
    单片机与PLC的区别?
    FreeRTOS常用函数
    ADC采集电流相关知识
    CA和SSL证书介绍
    物联网设备的安全性预防(转)
  • 原文地址:https://www.cnblogs.com/baxianhua/p/10196720.html
Copyright © 2011-2022 走看看