python文件操做

1、讀文件:

raed()方法:
read()方法讀取整個文件返回字符串對象,若是文件內容大於可用內存,則會拋出異常,通常不建議這麼操做python

f = open('test.txt','r') #建立文件句柄,也是一個可迭代對象
try:
    content = f.read()  #結果爲str類型
    print (type(content))
    print (content)
finally:
    f.close()

with open('test.txt','r') as f:
    content = f.read()  #結果爲str類型
    print (type(content))
    print (content)

結果爲:
<type 'str'>
Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife,hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the fire that burns against the cold, the light that brings the dawn, the horn that wakes the sleepers, the shield that guards the realms of men. I pledge my life and honor to the Night’s Watch, for this night and all the nights to come.

readline()方法:
每次讀取一行,返回一個字符串對象,保存當前行的內容linux

f = open(r'aa.txt','r')
try:
  while True:
      line = f.readline()
      if line:
          print (line)
      else:
          break
finally:
    f.close()

with open(r'aa.txt','r') as f:
      while True:
          line = f.readline()
          if line:
              print (line)
          else:
              break 
結果爲:
Night gathers, and now my watch begins. It shall not end until my death. 

I shall take no wife,hold no lands, father no children. 

I shall wear no crowns and win no glory. 

I shall live and die at my post. 

I am the sword in the darkness. 

I am the watcher on the walls. 

I am the fire that burns against the cold, 

the light that brings the dawn, the horn that wakes the sleepers, the shield that guards the realms of men. 

I pledge my life and honor to the Night’s Watch, for this night and all the nights to come.

Night gathers, and now my watch begins. It shall not end until my death. 

I shall take no wife,hold no lands, father no children. 

I shall wear no crowns and win no glory. 

I shall live and die at my post. 

I am the sword in the darkness. 

I am the watcher on the walls. 

I am the fire that burns against the cold, 

the light that brings the dawn, the horn that wakes the sleepers, the shield that guards the realms of men. 

I pledge my life and honor to the Night’s Watch, for this night and all the nights to come.

由於readline是按行讀取,按行打印,而print函數默認輸出完,須要跨行!因此每打印一行中間都有空一行
readlines方法:
一次性讀取整個文件,自動將文件內容分析成一個行的列表,返回列表對象windows

f = open(r'aa.txt','r')
try:
  lines = f.readlines()
  print type(lines) 
  print (lines)
finally:
    f.close()

with open(r'aa.txt,'r') as f:
    lines = f.readlines()
    print type(lines)
    for line in lines:
        print (line)

對於大文件的讀取:
採用如下兩種方式:ide

1.按行讀取
with  open(r'aa.txt','r')   as f: 
    for line in f:
        print line

對可迭代對象 f,進行迭代遍歷:for line in f,會自動地使用緩衝IO(buffered IO)以及內存管理,而沒必要擔憂任何大文件的問題。
2.分批讀取,每次讀取固定
def read_in_size(filePath,size=1024*1024):   
    f = open(filePath)    
    while True:
        data = f.read(size)        
        if not data:            
            break        
        yield data

if __name__ == "__main__":    
    filePath = 'aa.txt' 
    for content in read_in_size(filePath):        
        print content

2、寫文件:

f = open(r'aa.txt','w')
f.write("hello world")
f.write("hhh")
f.close()
寫文件會自動地使用緩衝IO(buffered IO),就是說寫文件的時候會先寫入到緩衝區,這個咱們你們也知道磁盤io跟內存的讀寫效率不是一個級別的,若是每write如下就要等待磁盤io完成,這會影響程序效率,因此python默認會將寫入工做先放入內存緩衝區,達到緩衝區大小在寫入磁盤。

若是要求實時寫入,必須進行強制刷新。函數

f = open(r'aa.txt','w')
f.write("hello world")
f.write("hhh")
f.flush()
f.close()

這裏寫一個打印進度條的例子post

import sys,time
for i in range(50):
    sys.stdout.write("#")
    sys.stdout.flush()
    time.sleep(0.1)

python 的讀寫模式
'r' : 以只讀模式打開文件,只能讀取不能寫入
'w': 以寫入模式打開文件,只能寫入不能讀取,(會覆蓋文件以前的內容)
'r+': 以讀寫模式打開文件,可讀可寫,這裏的寫入是以追加的方式寫在文件末尾
'w+':以寫讀模式打開文件,可讀可寫,覆蓋文件以前的內容,以後寫入的內容可讀,可是寫入以後文件句柄指針就到了文件末尾,必須用seek方法回到文件的最初位置才能夠讀取,因此我的感受這個模式沒什麼卵用。
'a+':以追加寫的方式打開文件
'rb':以二進制讀模式打開文件,固然相應的有wb,ab,rb+,wb+,ab+
python2裏 'r' 跟 'rb'沒有多大區別,在python3裏由於引入了bytes類型,因此這兩個操做是有區別的。
'rU':讀取文件時自動將\r\n轉換成\n(在windows上換行是\r\n,在linux上換行是\n)
這裏舉一個例子this

f = open('test.txt','wb')
#錯誤寫入方式
f.write("hello,world")
#正確寫入方式
f.write("hello,world".encode() )
f.close()
python3裏必須用encode方法將str類型轉換成bytes類型才能以這種方式寫入。
相關文章
相關標籤/搜索