【问题标题】:open() "r+" option working incorrectlyopen() "r+" 选项工作不正常
【发布时间】:2014-07-17 21:56:37
【问题描述】:
$ python
Python 2.7.3 (default, Apr 10 2013, 05:46:21)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> c = open("/home/aditya/Documents/in.txt","r+")
>>> c.read()
'GNU and python are amazing.\n'
>>> c.write("Oh yes they are!")
>>> c.read()
''
>>> c.close()
>>>
aditya@aditya-Latitude-D620:~$

我在课程中了解到“r+”可以用于读写。但是,在我 write() 之后,我无法阅读它。 read() 方法返回一个空值。为什么会这样?

【问题讨论】:

    标签: python python-2.7 file-io io


    【解决方案1】:

    文件有一个位置。一读一写,地位就高了。

    除非你重新定位位置,否则下一个操作发生在当前位置。

    您可以使用file.seek 倒带文件。例如倒退到文件的开头:

    file_object.seek(0)
    

    【讨论】:

    • ,有没有办法将 seek() 到不同的行,比如 hello world\nhello python。我可以使用 seek 命令从第一行转到第二行吗
    • @adch99,我不明白你的意思。位置(偏移)应该是数字。 (正/负)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 2021-04-27
    • 1970-01-01
    相关资源
    最近更新 更多