现在的位置: 首页 > 综合 > 正文

002_001 Python 读取文件

2018年02月15日 ⁄ 综合 ⁄ 共 908字 ⁄ 字号 评论关闭

代码如下:

#encoding=utf-8
print '中国'

#读取文件

input = open(r'D:\123.txt','r')

#方式一
print '--------1'
while True:
    line = input.readline()
    if not line :
        break
    else:
        print line.decode('gbk')
        
#方式二
print '--------2'
input.seek(0)
for line in input.readlines():   
    print line.decode('gbk')
    
#方式三
print '--------3'
input.seek(0)
for line in input:
    print line.decode('gbk')
input.close() 

#方案四 全部读取 除非文件很大,建议读取内存处理比较快
print '--------4' 
input = open(r'D:\123.txt','r')
try:
    print input.read().decode('gbk')
finally:
    input.close()
    
#方案五读取二进制
print '--------5' 
input = open(r'D:\123.txt','rb')
try:
    print input.read(6).decode('gbk')
finally:
    input.close()

def read_file_by_chunks(filename,chunksize=100):
    fileobj = open(filename,'rb')   #ru的打开方式保证所有平台的换行符号为\n  
    while True:
        chunk = fileobj.read(chunksize)
        if not chunk:
            break
        yield chunk
    fileobj.close()

for chunk in read_file_by_chunks(r'D:\123.txt',6):
    print chunk.decode('gbk')

打印结果如下:

中国
--------1
123

456

中国

--------2
123

456

中国

--------3
123

456

中国

--------4
123
456
中国

--------5
123
4
123
4
56

抱歉!评论已关闭.