python對檔案操作

來源:互聯網
上載者:User

標籤:game   ESS   oserror   width   基本操作   代碼   set   表示   建立   

檔案操作:

對檔案操作流程

  1. 開啟檔案,得到檔案控制代碼並賦值給一個變數
  2. 通過控制代碼對檔案進行操作
  3. 關閉檔案

現有檔案如下

Somehow, it seems the love I knew was always the most destructive kind

不知為何,我經曆的愛情總是最具毀滅性的的那種

Yesterday when I was young

昨日當我年少輕狂

The taste of life was sweet

生命的滋味是甜的

As rain upon my tongue

就如舌尖上的雨露

I teased at life as if it were a foolish game

我戲弄生命 視其為愚蠢的遊戲

The way the evening breeze

就如夜晚的微風

May tease the candle flame

逗弄蠟燭的火苗

The thousand dreams I dreamed

我曾千萬次夢見

The splendid things I planned

那些我計劃的絢麗藍圖

I always built to last on weak and shifting sand

但我總是將之建築在易逝的流沙上

I lived by night and shunned the naked light of day

我夜夜笙歌 逃避白晝赤裸的陽光

And only now I see how the time ran away

基本操作  

f = open(‘lyrics‘) #開啟檔案

first_line = f.readline()

print(‘first line:‘,first_line) #讀一行

print(‘我是分隔線‘.center(50,‘-‘))

data = f.read()# 讀取剩下的所有內容,檔案大時不要用

print(data) #列印檔案

f.close() #關閉檔案

 

開啟檔案的模式有:

  • r,唯讀模式(預設)。
  • w,唯寫模式。【不可讀;不存在則建立;存在則刪除內容;】
  • a,追加模式。【可讀;   不存在則建立;存在則只追加內容;】

"+" 表示可以同時讀寫某個檔案

  • r+,可讀寫檔案。【可讀;可寫;可追加】
  • w+,寫讀
  • a+,同a

"U"表示在讀取時,可以將 \r \n \r\n自動轉換成 \n (與 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示處理二進位檔案(如:FTP發送上傳ISO鏡像檔案,linux可忽略,windows處理二進位檔案時需標註)

  • rb
  • wb
  • ab

其它文法

    def close(self): # real signature unknown; restored from __doc__        """        Close the file.                A closed file cannot be used for further I/O operations.  close() may be        called more than once without error.        """        pass    def fileno(self, *args, **kwargs): # real signature unknown        """ Return the underlying file descriptor (an integer). """        pass    def isatty(self, *args, **kwargs): # real signature unknown        """ True if the file is connected to a TTY device. """        pass    def read(self, size=-1): # known case of _io.FileIO.read        """        注意,不一定能全讀回來        Read at most size bytes, returned as bytes.                Only makes one system call, so less data may be returned than requested.        In non-blocking mode, returns None if no data is available.        Return an empty bytes object at EOF.        """        return ""    def readable(self, *args, **kwargs): # real signature unknown        """ True if file was opened in a read mode. """        pass    def readall(self, *args, **kwargs): # real signature unknown        """        Read all data from the file, returned as bytes.                In non-blocking mode, returns as much as is immediately available,        or None if no data is available.  Return an empty bytes object at EOF.        """        pass    def readinto(self): # real signature unknown; restored from __doc__        """ Same as RawIOBase.readinto(). """        pass #不要用,沒人知道它是幹嘛用的    def seek(self, *args, **kwargs): # real signature unknown        """        Move to new file position and return the file position.                Argument offset is a byte count.  Optional argument whence defaults to        SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values        are SEEK_CUR or 1 (move relative to current position, positive or negative),        and SEEK_END or 2 (move relative to end of file, usually negative, although        many platforms allow seeking beyond the end of a file).                Note that not all file objects are seekable.        """        pass    def seekable(self, *args, **kwargs): # real signature unknown        """ True if file supports random-access. """        pass    def tell(self, *args, **kwargs): # real signature unknown        """        Current file position.                Can raise OSError for non seekable files.        """        pass    def truncate(self, *args, **kwargs): # real signature unknown        """        Truncate the file to at most size bytes and return the truncated size.                Size defaults to the current file position, as returned by tell().        The current file position is changed to the value of size.        """        pass    def writable(self, *args, **kwargs): # real signature unknown        """ True if file was opened in a write mode. """        pass    def write(self, *args, **kwargs): # real signature unknown        """        Write bytes b to file, return number written.                Only makes one system call, so not all of the data may be written.        The number of bytes actually written is returned.  In non-blocking mode,        returns None if the write would block.        """        pass

with語句

為了避免開啟檔案後忘記關閉,可以通過管理上下文,即:

 

with open(‘log‘,‘r‘) as f:

...

如此方式,當with代碼塊執行完畢時,內部會自動關閉並釋放檔案資源。

在Python 2.7 後,with又支援同時對多個檔案的上下文進行管理,即:

 

with open(‘log1‘) as obj1, open(‘log2‘) as obj2:

pass

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.