读取文件:read()、readline()、readlines()、next()

时间:2021-05-16 19:32:24

1.read()

>>> f=open(r'D:\python36\projects\word_freq.txt').read()
>>> f
'争分夺秒\n灿烂夺目\n大好青春\n十里桃花\n西湖'    #以str类形式全部读取,带有'\n'
>>> type(f)
<class 'str'>

2.readline()

>>> l=open(r'D:\python36\projects\word_freq.txt').readline()
>>> l
'争分夺秒\n'                               #以str类形式读取一行,带有'\n'
>>> type(l)
<class 'str'>

3.readlines()

>>> n=open(r'D:\python36\projects\word_freq.txt').readlines()
>>> n
['争分夺秒\n', '灿烂夺目\n', '大好青春\n', '十里桃花\n', '西湖']
>>> type(n)                               #以列表类形式读取全部,带有'\n'
<class 'list'>

4.next()      

python3.6:next(f),参数f只是open()后的文件

>>> f=open(r'D:\python36\projects\word_freq.txt')	  
>>> l=next(f)	                          #str类形式读取下一行,带有'\n'  
>>> l	  
'争分夺秒\n'
>>> type(l)	  
<class 'str'>
>>

>>> f=open(r'D:\python36\projects\word_freq.txt') #这里的f只是open()后的文件	  
>>> next(f)                              #读取下一行,带有'\n'	  
'争分夺秒\n'
>>> next(f)                       	  
'灿烂夺目\n'
>>> next(f)	  
'大好青春\n'
>>> next(f)	  
'十里桃花\n'
>>> next(f)	  
'西湖'

python2.7:f.next(),f只是open()后的文件

>>> f = io.open(r'word_freq.txt')         #这里的f只是open()后的文件
>>> print(f.next())                       #读取下一行,带有'\n'
曲咪新乳膏
>>> print(f.next())
双黄连
>>> print(f.next())
二甲双胍
>>> 

readline()和next()的合用

>>> f=open(r'D:\python36\projects\word_freq.txt')	  
>>> f.readline()                          #readline()读取第一行	  
'争分夺秒\n'
>>> next(f)                               #next()读取下一行	  
'灿烂夺目\n'
>>> next(f)	  
'大好青春\n'
>>> next(f)	  
'十里桃花\n'
>>>