python3读取本地文件_Python读取文件的三种方式

深度学习往往需要处理各种类型的数据,比如XML,txt,json等等。这里介绍利用Python读取文本文件内容的三种方法:read()、readline() 和 readlines()。

假设 sxl.txt文件内容如下:

i like the movie

i ate an egg

read()方法

read()方法表示一次读取文件全部内容,该方法返回字符串。

f = open("sxl.txt")

lines = f.read()

print lines

print(type(lines))

f.close()

输出结果:

i like the movie

i ate an egg

readline()方法

该方法每次读出一行内容,所以,读取时占用内存小,比较适合大文件,该方法返回一个字符串对象。

f = open("sxl.txt")

line = f.readline()

while line:

print (line)

print(type(line))

line = f.readline()

f.close()

输出结果:

i like the movie

i ate an egg

readlines()方法

readlines()方法读取整个文件所有行,保存在一个列表(list)变量中,每次读取一行,但读取大文件会比较占内存。

f = open("sxl.txt")

lines = f.readlines()

for line in lines:

print (line)

print(type(line))

f.close()

输出结果:

i like the movie

i ate an egg

最后还有一种方式,与第三种方法类似。

f = open("sxl.txt")

print (type(f))

for line in f:

print (line)

print(type(line))

f.close()

输出结果:

i like the movie

i ate an egg

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值