Read File in Python

来源:互联网 发布:卖毛线比较好的淘宝店 编辑:程序博客网 时间:2024/05/17 07:50
  1. consider file object as an iterator
with open(...) as f:    for line in f:        <do something with line>

The with statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f treats the file object f as an iterable, which automatically uses buffered IO and memory management so you don’t have to worry about large files.

2.the difference between read,readline and readlines
read: read all of the file
readline:read next line
readlines: read all the file in a iterator

123.txt

lalalagwhwhwhwhwh

read

f = open('123.txt','r')a = f.read()a[out]:'lalala\ng\nwhwhwhwhwh'

readline

f = open('123.txt','r')a1 = f.readline()a1[out] lalalaa2 = f.readline()a2[out] ga3 = f.readline()a3[out] whwhwhwhwh

readlines

f = open('123.txt','r')a = f.readlines()a[out] ['lalala','g','whwhwhwhwh']type(a)[out] <type 'list'>
0 0