【发布时间】:2017-03-30 19:33:13
【问题描述】:
我有这个代码
with codecs.open("file.json", mode='a+', encoding='utf-8') as f:
我想要:
1) 如果文件不存在,则创建文件,并从文件开头开始写入。
2) 如果存在,先读取它并截断它,然后再写一些东西。
我在某个地方找到了这个
``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.
a+ 模式最适合我,但它只能让我写在文件末尾,
在a+模式下,我打开文件后立即有这个f.seek(0),但它没有影响,它不会寻找文件的开头。
【问题讨论】:
-
@StamKaly,你从哪里得到的?
-
@AhsanulHaque 他删除了他的评论哈哈
标签: python python-2.7 file io