zoukankan      html  css  js  c++  java
  • python3 下的文件输入输出特性以及如何覆盖文件内容和接下去输入

      今天碰到了一个非常有意思的python特性。本来我是想打开一个文件,在文件的末尾接下去输入一些内容的,代码如下:

    f = open('test.txt', 'r+')
    f.write(content)
    f.close()

      结果发现无论我写什么东西,content的内容总是会从文件开头写入,并且覆盖掉原来的内容。查了官方文档,也不知道应该怎么做。

      但偶然间我发现了接到末尾写入的方法,代码如下:

    f = open('test.txt', 'r+')
    f.read()
    f.write(content)
    f.close()

      没错,只是添加了一行f.read(),之后你的write函数就会自动接到末尾进行写入了。去翻了下官方文档,貌似没有提及这个。

    read(size)

    Read and return at most size characters from the stream as a single str. If size is negative or None, reads until EOF.

    write(s)

    Write the string s to the stream and return the number of characters written.

  • 相关阅读:
    Ecplilse使用
    JDK安装
    浏览器的前世今生
    RethinkDB
    [css]兼容性
    【js】undefined
    String面试题
    SOS.dll(SOS 调试扩展)
    【ajax跨域】原因原理解决
    腾讯WEB前端开发三轮面试经历及面试题
  • 原文地址:https://www.cnblogs.com/Blaxon/p/5025777.html
Copyright © 2011-2022 走看看