您现在的位置是:首页 > 文章详情

Python文件和流

日期:2018-08-07点击:370

Treasuring every moment


open函数

open(name[,mode[,buffering]])

mode有四种模式可选择:

  • 'r' 读模式
  • 'w' 写模式
  • 'a' 追加模式
  • 'b' 二进制模式(可添加到其他模式中使用) 'rb' 可读二进制模式
  • '+' 读/写模式

>write():参数为写入的内容 >>> f = open('somefile.txt','w') f.write('Hello, ') 7 >>> f.write('World!') 6 >>> f.close() >writelines():参数为一个字符串列表,它会把所有的字符串写入文件,但不会增加新的行 

read():参数为指定读多少字符(字节)

>>> f = open('somefile.txt','r') >>> f.read(4) 'Hell' >>> f.read(1) 'o' >>> f.read() ', World!' 

readline():读一行,包括换行符也一起读进来
readlines():读取文件的所有行并将其转换为列表返回

管式输出

demo.py

import sys text = sys.stdin.read() words = text.split() wordcount=len(words) print('Wordcount:',wordcount,'Text:',text) 

somefile.txt

Hello,World!

运行程序

$ cat somefile.txt | python demo.py ('Wordcount:', 1, 'Text:', 'Hello,World!') 

可以看出,管道符号(|)将一个命令的标准输出和下一个命令的标准输入连接在一起了。

随机访问

以上对文件的操作都是把文件当成流来进行操作,只能按照从头到尾的顺序读取数据。但是我们可以使用类文件对象的方法seek和tell来直接访问感兴趣的部分。

seek(offset[,whence ]):这个方法把当前位置移动到由offset和whence定义的位置。Offset类是一个字节(字符)数,表示偏移量。whence默认是0,表示偏移量是从文件开头开始计算的(这是偏移量必须是非负的)。

>>> f = open('somefile.txt','w') >>> f.write('0123456789') >>> f.seek(5) >>> f.write('hello,world') >>> f.close() >>> f = open('somefile.txt') >>> f.read() '01234hello,world6789' 

tell():返回当前文件的位置

>>> f = open('somefile.txt') >>> f.read(3) '012' >>> f.read(2) '34' >>> f.tell() 5 
原文链接:https://yq.aliyun.com/articles/637551
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章