http://www.afterhoursprogramming.com/tutorial/Python/Reading-Files/
终于到了可以实用的阶段了,开心。
先写个小文件,内容如下
Hello, welcome to the new world.
I'm simon.
I'd like to be your friend.
上代码
f=open('notice.txt','r')#打开文件
print(f.read(1))
print(f.read(3))
print(f.read())
结果是
H
ell
o, welcome to the new world.
I'm simon.
I'd like to be your friend.
可以看出来,read方法读取的是上次剩下的,如果有参数则读取指定长度字符,如果没有参数,则读取全部。
下面看看readline方法
f=open('notice.txt','r')#打开文件
print(f.readline())
print('--------')
print(f.readline())
结果是
Hello, welcome to the new world.
--------
I'm simon.
值得注意的是,readline的输出带了一个换行。
在试下循环
f=open('notice.txt','r')#打开文件
myList=[]
print(myList)
for row in f:
myList.append(row)
print(myList)
结果是
[]
['Hello, welcome to the new world.\n', "I'm simon.\n", "I'd like to be your friend.\n"]
最后的最后,一定不要忘记使用close方法来关闭文件。
f=open('notice.txt','r')#打开文件
print(f.read(3))
print(f.readline())
f.close()