前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python使用基本文件方法

python使用基本文件方法

作者头像
用户8442333
发布2021-12-16 08:59:13
2720
发布2021-12-16 08:59:13
举报
文章被收录于专栏:python知识python知识

假如test.txt文件包含如下内容:

Welcome to this file

There is nothing here except

This stupid haiku

下面是基本读文件的方法:

代码语言:javascript
复制
# read(n) 指定参数
>>> f = open(r'I:\python\test.txt')
>>> f.read(7)
'Welcome'
>>> f.read(4)
' to '
>>> f.close()

# read() 不指定参数
>>> f = open(r'I:\python\test.txt')
>>> print f.read()
Welcome to this file
There is nothing here except
This stupid haiku
>>> f.close()

# readline() 
>>> f = open(r'I:\python\test.txt')
>>> for i in range(3):
    print str(i) + ':' + f.readline()

    
0:Welcome to this file

1:There is nothing here except

2:This stupid haiku
>>> f.close()

#readlines()
>>> import pprint
>>> pprint.pprint(open(r'I:\python\test.txt').readlines())
['Welcome to this file\n',
 'There is nothing here except\n',
 'This stupid haiku']

readline返回一行的字符串, readlines返回包含文件所有内容的字符串列表, 每个元素是一行的字符串。

pprint 模块的pprint方法将内容分成每个小项单行显示。

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档