Python基礎學習

來源:互聯網
上載者:User

標籤:讀寫檔案   star   love   代碼塊   index   fuse   yesterday   foo   shift   

檔案操作

   文字檔可儲存的資料量多得難以置信:天氣資料、交通資料、社會經濟資料、文學作品等. 每當需要分析後修改儲存在檔案中的資訊時,讀取檔案都很有用,對資料分析應用程式來說尤其如此. 學習檔案的處理,可以讓程式能夠快速地分析大量的資料.

1. 對檔案的操作流程:

    首先開啟檔案,得到檔案控制代碼並賦值給一個變數, 然後通過控制代碼對檔案進行操作,操作完畢後,最後關閉檔案.

 

現有檔案如下

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事到如今我才看清歲月是如何匆匆流逝Yesterday when I was young昨日當我年少輕狂So many lovely songs were waiting to be sung有那麼多甜美的曲兒等我歌唱So many wild pleasures lay in store for me有那麼多肆意的快樂等我享受And so much pain my eyes refused to see還有那麼多痛苦 我的雙眼卻視而不見I ran so fast that time and youth at last ran out我飛快地奔走 最終時光與青春消逝殆盡I never stopped to think what life was all about我從未停下腳步去思考生命的意義And every conversation that I can now recall如今回想起的所有對話Concerned itself with me and nothing else at all除了和我相關的 什麼都記不得了The game of love I played with arrogance and pride我用自負和傲慢玩著愛情的遊戲And every flame I lit too quickly, quickly died所有我點燃的火焰都熄滅得太快The friends I made all somehow seemed to slip away所有我交的朋友似乎都不知不覺地離開了And only now I‘m left alone to end the play, yeah只剩我一個人在台上來結束這場鬧劇Oh, yesterday when I was young噢 昨日當我年少輕狂So many, many songs were waiting to be sung有那麼那麼多甜美的曲兒等我歌唱So many wild pleasures lay in store for me有那麼多肆意的快樂等我享受And so much pain my eyes refused to see還有那麼多痛苦 我的雙眼卻視而不見There are so many songs in me that won‘t be sung我有太多歌曲永遠不會被唱起I feel the bitter taste of tears upon my tongue我嘗到了舌尖淚水的苦澀滋味The time has come for me to pay for yesterday終於到了付出代價的時間 為了昨日When I was young當我年少輕狂

基本操作

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基礎學習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.