2

Python文件读写--错误一 - AiqDota

 2 years ago
source link: https://www.cnblogs.com/aiqdota/p/16010559.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python文件读写--错误一

在学习python的文件读写操作的时候,我遇到了一点麻烦事,觉得可以记录下来,先上代码吧。

with open('test.txt') as file:
    file.write('test')
    print(file.read())

我的目的很简单,就是以默认的a模式打开文件,并在文件末尾写入'test',然后把最新的文件读出来,可谁知当我运行的时候,竟然报错。认真查阅书本,才想起来a模式是不支持read()的,然后修改为a+模式,代码如下:

with open('test.txt','a+') as file:
    file.write('test')
    print(file.read())

本以为又要成功了,谁知内容是写进去了不错,但是输出是空的,就是文件读不出来。问了高人后,又是一个细节暴露了出来。原来这里牵涉到读写模式对文件中指针位置的影响,大家可以到网上搜一下,这里我只讲a+模式。a+模式以追加的模式打开一个文件用于读写。如果文件存在,则打开文件,将文件指针定位在文件尾,新写入的内容在原有内容的后面;如果文件不存在,则创建一个新文件用于读写。read()是从光标处向后读,也就是说read()之前,光标已经到了文件的末尾,因此也就读不出来内容了。这里我们要用到seek(0)来把光标重置到文件开头。最终代码如下:

with open('test.txt','a+') as file:
    file.write('test')
    file.seek(0)
    print(file.read())

终于正常了,哈哈,希望自己可以永远记住这几点。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK