python读文件的几种方式

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读文件的几种方式)