`

一个小脚本遇到的问题之python读写文本

阅读更多
   
    程序在这里
    上篇:如何查看网页编码(未验证)概不负责
    这次讨论的就是python中文件的读取和写入。因为只是修改了文件的很小一部分,所以我开始的想法就是最好能够只修改指定的行,而对于其他的内容则不修改。我这里不修改的意思是不用全部读取。想法很美好,现实却很残酷。经过搜索和询问,应该是没有可能。
    在python中对于文件的内容修改,只能全部读取后修改,然后写入。
    如果能有更简单的方法,请不吝赐教。

    另一个也是文本操作问题,本来以为把文本的打开模式设置为r+,这样就可以先读取,然后再写入。可结果是读取完后,写入则直接到了文件的最后。类似于添加内容,而我的想法是覆盖。搜索了这个问题,发现想当然的又不成立。具体几个模式的意思如下:
    原文地址:http://stackoverflow.com/a/1466036

# 摘自stackoverflow,原文地址为:http://stackoverflow.com/a/1466036
The opening modes are exactly the same that C fopen() std library function.

The BSD fopen manpage defines them as follows:

 The argument mode points to a string beginning with one of the following
 sequences (Additional characters may follow these sequences.):

 ``r''   Open text file for reading.  The stream is positioned at the
         beginning of the file.

 ``r+''  Open for reading and writing.  The stream is positioned at the
         beginning of the file.

 ``w''   Truncate file to zero length or create text file for writing.
         The stream is positioned at the beginning of the file.

 ``w+''  Open for reading and writing.  The file is created if it does not
         exist, otherwise it is truncated.  The stream is positioned at
         the beginning of the file.

 ``a''   Open for writing.  The file is created if it does not exist.  The
         stream is positioned at the end of the file.  Subsequent writes
         to the file will always end up at the then current end of file,
         irrespective of any intervening fseek(3) or similar.

 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  The stream is positioned at the end of the file.  Subse-
         quent writes to the file will always end up at the then current
         end of file, irrespective of any intervening fseek(3) or similar.


    还有一个图片,也很不错,更简单。地址是:http://stackoverflow.com/a/30566011


  • 大小: 68.9 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics