由python文件模式“w +”混淆 [英] Confused by python file mode "w+"

查看:233
本文介绍了由python文件模式“w +”混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档


模式'r +','w +'和'a +'打开文件进行更新(注意'w +'截断文件)。在二进制模式下,在区分二进制文件和文本文件的系统上追加b到打开文件的模式;在没有这种区别的系统上,添加'b'没有任何效果。

Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the 'b' has no effect.

here


w +:打开一个写作和阅读的文件。如果文件存在,则覆盖现有文件。如果文件不存在,请创建一个新文件进行阅读和写入。

w+ : Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

但是,如何使用 W +

推荐答案

假设您使用语句打开文件就像你应该是。那么你可以这样做从文件中读取:

Let's say you're opening the file with a with statement like you should be. Then you'd do something like this to read from your file:

with open('somefile.txt', 'w+') as f:
    # Note that f has now been truncated to 0 bytes, so you'll only
    # be able to read data that you wrote earlier...
    f.write('somedata\n')
    f.seek(0)  # Important: return to the top of the file before reading, otherwise you'll just read an empty string
    data = f.read() # Returns 'somedata\n'

请注意 f.seek(0 ) - 如果您忘记了这一点, f.read()调用将尝试从文件末尾读取,并返回空字符串。

Note the f.seek(0) -- if you forget this, the f.read() call will try to read from the end of the file, and will return an empty string.

这篇关于由python文件模式“w +”混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆