如何从“a+"中打开的文件中读取模式? [英] How to read from file opened in "a+" mode?

查看:30
本文介绍了如何从“a+"中打开的文件中读取模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据定义,a+"模式打开文件以进行追加和读取.追加有效,但阅读的方法是什么?我进行了一些搜索,但在任何地方都找不到澄清的内容.

By definition, "a+" mode opens the file for both appending and reading. Appending works, but what is the method for reading? I did some searches, but couldn't find it clarified anywhere.

f=open("myfile.txt","a+")
print (f.read())

试过这个,它打印空白.

Tried this, it prints blank.

推荐答案

使用 f.seek() 设置文件偏移到文件开头.

Use f.seek() to set the file offset to the beginning of the file.

注意:在 Python 2.7 之前,有一个 bug 会导致某些操作系统不会让文件位置始终指向文件末尾.这可能会导致某些用户使用您的原始代码.例如,在 CentOS 6 上,您的代码会按您的意愿运行,但不会按预期运行.

Note: Before Python 2.7, there was a bug that would cause some operating systems to not have the file position always point to the end of the file. This could cause some users to have your original code work. For example, on CentOS 6 your code would have worked as you wanted, but not as it should.

f = open("myfile.txt","a+")
f.seek(0)
print f.read()

这篇关于如何从“a+"中打开的文件中读取模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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