照葫芦画瓢-reading files(读文件)

本文介绍了使用Python进行文件读取的基本方法,包括read、readline及循环读取等技巧,并展示了如何将文件内容逐行存储到列表中。

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()

 

转载于:https://my.oschina.net/u/3301706/blog/1593915

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值