python學習筆記(檔案)

來源:互聯網
上載者:User

標籤:

開啟檔案

open函數使用一個檔案名稱作為唯一的強制參數,返回一個檔案對象

文法:

file object = open(file_name [, access_mode][, buffering])

各個參數的細節如下:

file_name:file_name變數是一個包含了你要訪問的檔案名稱的字串值。

access_mode:access_mode決定了開啟檔案的模式:唯讀,寫入,追加等。所有可取值見如下的完全列表。這個參數是非強制的,預設檔案訪問模式為唯讀(r)。

buffering:如果buffering的值被設為0,就不會有寄存。如果buffering的值取1,訪問檔案時會寄存行。如果將buffering的值設為大於1的整數,表明了這就是的寄存區的緩衝大小。如果取負值,寄存區的緩衝大小則為系統預設。

open函數使用一個檔案名稱作為唯一的強制參數,然後返回一個檔案對象。假設我要開啟我硬碟(F:\python\myDemo\game.txt) 檔案,可以用下面方法:

>>> f=open(r‘F:\python\myDemo\game.txt‘)
檔案模式

open 函數除了必須提供的檔案名稱參數外,其實還有一個 mode 的模式參數,如果沒有指定參數值的話,它的預設值是: rmode參數的可選值如下:

‘r‘                  讀模式‘w‘                  寫入模式‘a‘                  追加模式‘b‘                  二進位模式(可添加到其他模式使用)‘+‘                  讀/寫入模式(可添加其他模式使用)
緩衝

open 函數的第三個參數( buffering ),表示檔案的緩衝,當緩衝區大於0時(等於0時無緩衝,所有的讀寫操作都直接針對硬碟),Python會將檔案內容存放到緩衝區(記憶體中),從而是程式啟動並執行的更快,這時,只有使用 flush 或者 close 時才會將緩衝區中的資料更新到硬碟中。

基本檔案方法

讀和寫

Write()方法

Write()方法可將任何字串寫入一個開啟的檔案。需要重點注意的是,Python字串可以是位元據,而不是僅僅是文字。

Write()方法不在字串的結尾不添加分行符號(‘\n‘):

>>> f=open(‘somefile.txt‘,‘wb‘)>>> f.write(‘Python is a great language.\nYeah its great!!\n‘)>>> f.close()>>> 
read()方法

read()方法從一個開啟的檔案中讀取一個字串。需要重點注意的是,Python字串可以是位元據,而不是僅僅是文字。

>>> f=open(‘somefile.txt‘,‘r+‘)>>> str=f.read(10)>>> print ‘Read String is : ‘,strRead String is :  Python is >>> f.close()>>> 
Close()方法

File對象的close()方法重新整理緩衝區裡任何還沒寫入的資訊,並關閉該檔案,這之後便不能再進行寫入。

當一個檔案對象的引用被重新指定給另一個檔案時,Python會關閉之前的檔案。用close()方法關閉檔案是一個很好的習慣。

>>> f=open(‘foo.txt‘,‘wb‘)>>> print ‘Name of the file: ‘,f.nameName of the file:  foo.txt>>> f.close()
檔案位置:

Tell()方法告訴你檔案內的當前位置;換句話說,下一次的讀寫會發生在檔案開頭這麼多位元組之後:

seek(offset [,from])方法改變當前檔案的位置。Offset變數表示要移動的位元組數。From變數指定開始移動位元組的參考位置。

如果from被設為0,這意味著將檔案的開頭作為移動位元組的參考位置。如果設為1,則使用當前的位置作為參考位置。如果它被設為2,那麼該檔案的末尾將作為參考位置。

>>> f=open(‘somefile.txt‘,‘r+‘)   #開啟檔案>>> str=f.read(10)>>> print ‘Read String is :‘,strRead String is : Python is >>> position=f.tell()     #尋找檔案位置>>> print ‘Current file position : ‘,positionCurrent file position :  8>>> position=f.seek(0,0);  #把指標再次定位到檔案開頭>>> str=f.read(10)>>> print ‘Again read String is : ‘,strAgain read String is :  Python is >>> f.close()  #關閉檔案>>> 
使用基本檔案方法

假如somefilet.txt檔案包含如下內容:

-----------------------------

Welcome to this file

There is nothing here except

This stupid haiku

-----------------------------

>>> f=open(r‘f:\python\myDemo\somefile.txt‘)>>> f.read(7)‘Welcome‘>>> f.close()>>> f=open(r‘f:\python\myDemo\somefile.txt‘)>>> f.read()‘Welcome to this file\n\nThere is nothing here except\n\nThis stupid haiku‘>>> f.close()>>> f=open(r‘f:\python\myDemo\somefile.txt‘)>>> for i in range(3):    print str(i) +‘:‘ +f.readline()    0:Welcome to this file1:2:There is nothing here except>>> f.close()>>> import pprintpprint.pprint(open(r‘f:\python\myDemo\somefile.txt‘).readlines())[‘Welcome to this file\n‘, ‘\n‘, ‘There is nothing here except\n‘, ‘\n‘, ‘This stupid haiku‘]>>>

  >>> f=open(‘f:\python\myDemo\somefile.txt‘,‘w‘)
  >>> f.write(‘this\nis no\nhaiku‘)
  >>> f.close()
  >>> f=open(r‘f:\python\myDemo\somefile.txt‘)
  >>> lines=f.readlines()
  >>> f.close()
  >>> lines[1]
  ‘is no\n‘
  >>> lines[1]=‘isn\‘t a\n‘
  >>> f=open(r‘f:\python\myDemo\somefile.txt‘,‘w‘)
  >>> f.writelines(lines)
  >>> f.close()
  >>>

  -----

  this

  isn‘t a

  haiku

 

對檔案內容進行迭代  按位元組處理

最常見的對檔案內容進行迭代的方法是while迴圈中使用read方法。例如,對每個字元進行迴圈,可以用下面方法實現:

f=open(filename)char=f.read(1)while char:    process(char)    char =f.read(1)f.close()

  read方法返回的字串會包含一個字元,直到檔案末尾,read返回一個空的字串,char將變為假。


  可以看到,char = f.read(1) 被重複地使用,代碼重複通過被認為是一件壞事,看看下面的方法:

#不同的方式寫迴圈f=open(filename)while True:    char=f.read(1)    if not char: break    process(char)f.close()
按行操作
f=open(filename)while True:    line=f.readline()    if not line: break    process(line)f.close()
讀取所有內容

如果檔案不是很大,那麼可以使用不帶參數的read方法一次讀取整個檔案,或者使用readlines方法。

f=open(filename)for char in f.read():    process(char)f.close()#用readlines迭代行f=open(filename)for line in f.readlines():    process(line)f.close()
按需載入并迭代

對檔案內容進行按需載入,而不是一次性的將其從讀到記憶體的中好處之一就是可以按需載入,節省系統資源,特別是對一些超大的檔案來說更是如此。如果對大檔案進行迭代操作可以考慮下面的兩種方式:

用fileinput 來進行迭代

需要對一個非常大的檔案進行迭代時,使用 readlines 會佔用過多的記憶體,這時候除了可以用 while 迴圈和 readline 來替代,還可以通過使用for 迴圈和 fileinput 模組來實現懶惰迭代——即按需迭代:

import fileinputfor line in fileinput.input(filename):    process(line)
使用檔案迭代器
f=open(r‘f:\python\myDemo\somefile.txt‘)for line in f:    print linef.close()    

 

python學習筆記(檔案)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.