被python文件模式“w+"搞糊涂了; [英] Confused by python file mode "w+"

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

问题描述

来自 doc

模式'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.

这里

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+ 打开的文件?

But, how to read a file open with w+?

推荐答案

假设您正在使用 with 语句打开文件,就像您应该的那样.然后你会做这样的事情来从你的文件中读取:

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 write after this point
    f.write('somedata
')
    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
'

请注意 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天全站免登陆