文件(二)

读取文件

1、一次性读取整个文件file.read()

>>> fp = open("e:\\python\\hu.txt","r")
>>> content = fp.read()
>>> print content

看见
sfs
sfdds
1-1读取指定字节数file.read(count)
count为每次读取的字节数

>>> file_obj = open("e:\\python\\3.txt","r")
>>> file_obj.read(5)
'123\n8'

2、依次读取每行文件,存入一个列表,列表中的每个元素是一行file.readlines()

>>> file_obj = open("e:\\python\\3.txt","r")
>>> contents = file_obj.readlines()
>>> for content in contents:
...     print content
...

123
3、读取单行文件,file.readline()

>>> file_obj = open("e:\\python\\3.txt","r")
>>> b=file_obj.readline()
>>> b

'123\n'
4、利用文件对象名遍历文件

>>> file_obj = open("e:\\python\\3.txt","r")
>>> for cotent in file_obj:
...     print content
...

猜你喜欢

转载自blog.51cto.com/13496943/2133253
今日推荐