1. 程式人生 > >文件(二)

文件(二)

一個 nes 一次 tro () 字節數 pen 元素 TE

讀取文件

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
...

文件(二)