美文网首页
python读文件的几种方式

python读文件的几种方式

作者: 高稚商de菌 | 来源:发表于2018-03-07 00:39 被阅读0次

There should be one-- and preferably only one --obvious way to do it.(from The Zen of Pyhton)

python中读文件的方式有很多种, 这里整理一下。

# 直接读整个文件
# 如果文件比较大,会占用大量的内存
with open('somefile.txt') as f:
     print f.read()
this is a test file
this is a test file
this is a test file
# 读整个文件, 返回一个list
# 读大文件也会比较占内存
# 其实readlines也可以指定size字节数, 不常用
with open('somefile.txt') as f:
    for line in f.readlines():
        print line.strip()
this is a test file
this is a test file
this is a test file
# 一次读1024字节
with open('somefile.txt') as f:
    while True:
        txt = f.read(1024)
        if txt == '':
            break
        print txt
this is a test file
this is a test file
this is a test file
# 一次读一行
# readline也可以指定size字节数, 不常用
with open('somefile.txt') as f:
    while True:
        line = f.readline()
        if line == '':
            break
        print line.strip()
this is a test file
this is a test file
this is a test file
# 一次读一行, 读大文件时推荐
with open('somefile.txt') as f:
    for line in f:
        print line.strip()
this is a test file
this is a test file
this is a test file

相关文章

网友评论

      本文标题:python读文件的几种方式

      本文链接:https://www.haomeiwen.com/subject/zutdfftx.html