<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                # Python 文件 I/O > 原文: [https://www.programiz.com/python-programming/file-operation](https://www.programiz.com/python-programming/file-operation) #### 在本教程中,您將學習 Python 文件操作。 更具體地說,打開文件,讀取文件,寫入文件,關閉文件以及您應該注意的各種文件方法。 ## 文件 文件被命名為磁盤上用于存儲相關信息的位置。 它們用于將數據永久存儲在非易失性存儲器(例如硬盤)中。 由于隨機存取存儲器(RAM)是易失性的(當計算機關閉時會丟失其數據),因此我們通過永久存儲文件來使用文件以備將來使用。 當我們要讀取或寫入文件時,我們需要先打開它。 完成后,需要關閉它,以便釋放與文件綁定的資源。 因此,在 Python 中,文件操作按以下順序進行: 1. 打開文件 2. 讀取或寫入(執行操作) 3. 關閉文件 * * * ## 用 Python 打開文件 Python 具有內置的`open()`函數來打開文件。 此函數返回文件對象,也稱為句柄,因為它用于相應地讀取或修改文件。 ```py >>> f = open("test.txt") # open file in current directory >>> f = open("C:/Python38/README.txt") # specifying full path ``` 我們可以在打開文件時指定模式。 在模式下,我們指定是要讀取`r`,寫入`w`還是將`a`附加到文件中。 我們還可以指定是否要以文本模式或二進制模式打開文件。 默認為在文本模式下閱讀。 在這種模式下,當從文件中讀取時,我們會得到字符串。 另一方面,二進制模式返回字節,這是處理非文本文件(例如圖像或可執行文件)時要使用的模式。 | 模式 | 描述 | | --- | --- | | `r` | 打開文件進行讀取。 (默認) | | `w` | 打開一個文件進行寫入。 如果不存在則創建一個新文件,或者如果存在則將其截斷。 | | `x` | 打開文件以進行獨占創建。 如果文件已經存在,則操作失敗。 | | `a` | 打開文件以在文件末尾附加而不截斷。 如果不存在,則創建一個新文件。 | | `t` | 以文本模式打開。 (默認) | | `b` | 以二進制模式打開。 | | `+` | 打開文件進行更新(讀取和寫入) | ```py f = open("test.txt") # equivalent to 'r' or 'rt' f = open("test.txt",'w') # write in text mode f = open("img.bmp",'r+b') # read and write in binary mode ``` 與其他語言不同,字符`a`直到使用`ASCII`(或其他等效編碼)編碼后才隱含數字 97。 此外,默認編碼取決于平臺。 在 Windows 中,它是`cp1252`,在 Linux 中是`utf-8`。 因此,我們也不能依賴默認編碼,否則我們的代碼在不同平臺上的行為會有所不同。 因此,在以文本模式處理文件時,強烈建議指定編碼類型。 ```py f = open("test.txt", mode='r', encoding='utf-8') ``` * * * ## 在 Python 中關閉文件 完成對文件的操作后,我們需要正確關閉文件。 關閉文件將釋放與該文件綁定的資源。 這是使用 Python 中可用的`close()`方法完成的。 Python 有一個垃圾收集器來清理未引用的對象,但是我們不能依靠它來關閉文件。 ```py f = open("test.txt", encoding = 'utf-8') # perform file operations f.close() ``` 這種方法并不完全安全。 如果對文件執行某些操作時發生異常,則代碼將退出而不關閉文件。 一種更安全的方法是使用 [try ... finally](/python-programming/exception-handling) 塊。 ```py try: f = open("test.txt", encoding = 'utf-8') # perform file operations finally: f.close() ``` 這樣,即使出現引發導致程序流停止的異常,我們也可以保證文件已正確關閉。 關閉文件的最佳方法是使用`with`語句。 這樣可以確保退出`with`語句內的塊時關閉文件。 我們不需要顯式調用`close()`方法。 它是在內部完成的。 ```py with open("test.txt", encoding = 'utf-8') as f: # perform file operations ``` * * * ## 用 Python 寫入文件 為了使用 Python 寫入文件,我們需要以寫入`w`,附加`a`或互斥創建`x`模式打開它。 我們需要特別注意`w`模式,因為如果它已經存在,它將覆蓋到文件中。 因此,所有先前的數據都將被擦除。 寫入字符串或字節序列(對于二進制文件)是使用`write()`方法完成的。 此方法返回寫入文件的字符數。 ```py with open("test.txt",'w',encoding = 'utf-8') as f: f.write("my first file\n") f.write("This file\n\n") f.write("contains three lines\n") ``` 如果該程序不存在,它將在當前目錄中創建一個名為`test.txt`的新文件。 如果確實存在,則將其覆蓋。 我們必須自己包括換行符,以區分不同的行。 * * * ## 用 Python 讀取文件 要使用 Python 讀取文件,我們必須以讀取`r`模式打開文件。 有多種方法可用于此目的。 我們可以使用`read(size)`方法讀取`size`數的數據。 如果未指定`size`參數,它將讀取并返回文件末尾。 我們可以通過以下方式讀取在上一節中編寫的`text.txt`文件: ```py >>> f = open("test.txt",'r',encoding = 'utf-8') >>> f.read(4) # read the first 4 data 'This' >>> f.read(4) # read the next 4 data ' is ' >>> f.read() # read in the rest till end of file 'my first file\nThis file\ncontains three lines\n' >>> f.read() # further reading returns empty sting '' ``` 我們可以看到`read()`方法返回一個換行符`'\n'`。 到達文件末尾后,我們將得到一個空字符串,供進一步閱讀。 我們可以使用`seek()`方法更改當前文件的光標(位置)。 同樣,`tell()`方法返回我們的當前位置(以字節數為單位)。 ```py >>> f.tell() # get the current file position 56 >>> f.seek(0) # bring file cursor to initial position 0 >>> print(f.read()) # read the entire file This is my first file This file contains three lines ``` 我們可以使用[循環](/python-programming/for-loop)逐行讀取文件。 這既高效又快速。 ```py >>> for line in f: ... print(line, end = '') ... This is my first file This file contains three lines ``` 在此程序中,文件本身的行包含換行符`\n`。 因此,我們在打印時使用`print()`函數的`end`參數來避免出現兩個換行符。 另外,我們可以使用`readline()`方法讀取文件的各個行。 此方法讀取文件,直到換行符為止,包括換行符。 ```py >>> f.readline() 'This is my first file\n' >>> f.readline() 'This file\n' >>> f.readline() 'contains three lines\n' >>> f.readline() '' ``` 最后,`readlines()`方法返回整個文件剩余行的列表。 當到達文件末尾(EOF)時,所有這些讀取方法都將返回空值。 ```py >>> f.readlines() ['This is my first file\n', 'This file\n', 'contains three lines\n'] ``` * * * ## Python 文件方法 文件對象有多種可用方法。 其中一些已在以上示例中使用。 這是文本模式下方法的完整列表,并帶有簡要說明: | 方法 | 描述 | | --- | --- | | `close()` | 關閉打開的文件。 如果文件已經關閉,則無效。 | | `detach()` | 將底層二進制緩沖區與`TextIOBase`分離并返回。 | | `fileno()` | 返回文件的整數(文件描述符)。 | | `flush()` | 刷新文件流的寫緩沖區。 | | `isatty()` | 如果文件流是交互式的,則返回`True`。 | | `read(n)` | 從文件中讀取最多`n`個字符。 如果為負或`None`則讀取到文件末尾。 | | `readable()` | 如果可以讀取文件流,則返回`True`。 | | `readline(n=-1)` | 從文件讀取并返回一行。 如果指定,則最多讀入`n`個字節。 | | `readlines(n=-1)` | 從文件讀取并返回行列表。 如果指定,則最多讀入`n`個字節/字符。 | | `seek(offset,from=SEEK_SET)` | 參考`from`(開始,當前,結束),將文件位置更改為`offset`字節。 | | `seekable()` | 如果文件流支持隨機訪問,則返回`True`。 | | `tell()` | 返回當前文件位置。 | | `truncate(size=None)` | 將文件流調整為`size`字節。 如果未指定`size`,則將其尺寸調整為當前位置。 | | `writable()` | 如果可以寫入文件流,則返回`True`。 | | `write(s)` | 將字符串`s`寫入文件,并返回寫入的字符數。 | | `writelines(lines)` | 將`lines`的列表寫入文件。 |
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看