<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>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Python:如何讀取和寫入文件 > 原文: [https://thepythonguru.com/python-how-to-read-and-write-files/](https://thepythonguru.com/python-how-to-read-and-write-files/) * * * 于 2020 年 1 月 7 日更新 * * * 在本文中,我們將學習如何在 Python 中讀取和寫入文件。 處理文件包括以下三個步驟: 1. 打開文件 2. 執行讀或寫操作 3. 關閉文件 讓我們詳細了解每個步驟。 ## 文件類型 * * * 有兩種類型的文件: 1. 文本文件 2. 二進制文件 文本文件只是使用 utf-8,latin1 等編碼存儲字符序列的文件,而對于二進制文件,數據以與計算機內存相同的格式存儲。 以下是一些文本和二進制文件示例: 文本文件:Python 源代碼,HTML 文件,文本文件,降價文件等。 二進制文件:可執行文件,圖像,音頻等 重要的是要注意,在磁盤內部,兩種類型的文件都以 1 和 0 的順序存儲。 唯一的區別是,當打開文本文件時,將使用與編碼相同的編碼方案對數據進行解碼。但是,對于二進制文件,不會發生這種情況。 ## 打開文件 - `open()`函數 * * * `open()`內置函數用于打開文件。 其語法如下: ```py open(filename, mode) -> file object ``` 成功時,`open()`返回文件對象。 如果失敗,它將引發`IOError`或它的子類。 | 參數 | 描述 | | --- | --- | | `filename` | 要打開的文件的絕對或相對路徑。 | | `mode` | (可選)模式是一個字符串,表示處理模式(即讀取,寫入,附加等)和文件類型。 | 以下是`mode`的可能值。 | 模式 | 描述 | | --- | --- | | `r` | 打開文件進行讀取(默認)。 | | `w` | 打開文件進行寫入。 | | `a` | 以附加模式打開文件,即在文件末尾添加新數據。 | | `r+` | 打開文件以進行讀寫 | | `x` | 僅在尚不存在的情況下,打開文件進行寫入。 | 我們還可以將`t`或`b`附加到模式字符串以指示將要使用的文件的類型。 `t`用于文本文件,`b`用于二進制文件。 如果未指定,則默認為`t`。 `mode`是可選的,如果未指定,則該文件將作為文本文件打開,僅供讀取。 這意味著對`open()`的以下三個調用是等效的: ```py # open file todo.md for reading in text mode open('todo.md') open('todo.md', 'r') open('todo.md', 'rt') ``` 請注意,在讀取文件之前,該文件必須已經存在,否則`open()`將引發`FileNotFoundError`異常。 但是,如果打開文件進行寫入(使用`w`,`a`或`r+`之類的模式),Python 將自動為您創建文件。 如果文件已經存在,則其內容將被刪除。 如果要防止這種情況,請以`x`模式打開文件。 ## 關閉文件 - `close()`方法 * * * 處理完文件后,應將其關閉。 盡管程序結束時該文件會自動關閉,但是這樣做仍然是一個好習慣。 無法在大型程序中關閉文件可能會出現問題,甚至可能導致程序崩潰。 要關閉文件,請調用文件對象的`close()`方法。 關閉文件將釋放與其相關的資源,并將緩沖區中的數據刷新到磁盤。 ## 文件指針 * * * 通過`open()`方法打開文件時。 操作系統將指向文件中字符的指針關聯。 文件指針確定從何處進行讀取和寫入操作。 最初,文件指針指向文件的開頭,并隨著我們向文件讀取和寫入數據而前進。 在本文的后面,我們將看到如何確定文件指針的當前位置,并使用它來隨機訪問文件的各個部分。 ## 使用`read()`,`readline()`和`readlines()`讀取文件 * * * 要讀取數據,文件對象提供以下方法: | 方法 | 參數 | | --- | --- | | `read([n])` | 從文件讀取并返回`n`個字節或更少的字節(如果沒有足夠的字符讀取)作為字符串。 如果未指定`n`,它將以字符串形式讀取整個文件并將其返回。 | | `readline()` | 讀取并返回字符,直到以字符串形式到達行尾為止。 | | `readlines()` | 讀取并返回所有行作為字符串列表。 | 當到達文件末尾(EOF)時,`read()`和`readline()`方法返回一個空字符串,而`readlines()`返回一個空列表(`[]`)。 這里有些例子: **`poem.txt`** ```py The caged bird sings with a fearful trill of things unknown but longed for still ``` **示例 1** :使用`read()` ```py >>> >>> f = open("poem.txt", "r") >>> >>> f.read(3) # read the first 3 characters 'The' >>> >>> f.read() # read the remaining characters in the file. ' caged bird sings\nwith a fearful trill\nof things unknown\nbut longed for still\n' >>> >>> f.read() # End of the file (EOF) is reached '' >>> >>> f.close() >>> ``` **示例 2** :使用`readline()` ```py >>> >>> f = open("poem.txt", "r") >>> >>> f.read(4) # read first 4 characters 'The ' >>> >>> f.readline() # read until the end of the line is reached 'caged bird sings\n' >>> >>> f.readline() # read the second line 'with a fearful trill\n' >>> >>> f.readline() # read the third line 'of things unknown\n' >>> >>> f.readline() # read the fourth line 'but longed for still' >>> >>> f.readline() # EOF reached '' >>> >>> f.close() >>> ``` **示例 3** :使用`readlines()` ```py >>> >>> f = open("poem.txt", "r") >>> >>> f.readlines() ['The caged bird sings\n', 'with a fearful trill\n', 'of things unknown\n', 'but longed for still\n'] >>> >>> f.readlines() # EOF reached [] >>> >>> f.close() >>> ``` ## 批量讀取文件 * * * `read()`(不帶參數)和`readlines()`方法立即將所有數據讀入內存。 因此,請勿使用它們讀取大文件。 更好的方法是使用`read()`批量讀取文件,或使用`readline()`逐行讀取文件,如下所示: **示例**:讀取文件塊 ```py >>> >>> f = open("poem.txt", "r") >>> >>> chunk = 200 >>> >>> while True: ... data = f.read(chunk) ... if not data: ... break ... print(data) ... The caged bird sings with a fearful trill of things unknown but longed for still >>> ``` **示例**:逐行讀取文件 ```py >>> >>> f = open("poem.txt", "r") >>> >>> while True: ... line = f.readline() ... if not line: ... break ... print(line) ... The caged bird sings with a fearful trill of things unknown but longed for still >>> ``` 除了使用`read()`(帶有參數)或`readline()`方法之外,您還可以使用文件對象一次遍歷一行的文件內容。 ```py >>> >>> f = open("poem.txt", "r") >>> >>> for line in f: ... print(line, end="") ... The caged bird sings with a fearful trill of things unknown but longed for still >>> ``` 該代碼與前面的示例等效,但是更加簡潔,易讀且易于鍵入。 **警告**: 提防`readline()`方法,如果您在打開沒有任何換行符的大文件時遇到不幸,那么`readline()`并不比`read()`好(無參數)。 當您使用文件對象作為迭代器時,也是如此。 ## 使用`write()`和`writelines()`寫入數據 * * * 為了寫入數據,文件對象提供了以下兩種方法: | 方法 | 描述 | | --- | --- | | `write(s)` | 將字符串`s`寫入文件并返回寫入的數字字符。 | | `writelines(s)` | 將序列`s`中的所有字符串寫入文件。 | 以下是示例: ```py >>> >>> f = open("poem_2.txt", "w") >>> >>> f.write("When I think about myself, ") 26 >>> f.write("I almost laugh myself to death.") 31 >>> f.close() # close the file and flush the data in the buffer to the disk >>> >>> >>> f = open("poem_2.txt", "r") # open the file for reading >>> >>> data = f.read() # read entire file >>> >>> data 'When I think about myself, I almost laugh myself to death.' >>> >>> print(data) When I think about myself, I almost laugh myself to death. >>> >>> f.close() >>> ``` 請注意,與`print()`函數不同,`write()`方法不會在行尾添加換行符(`\n`)。 如果需要換行符,則必須手動添加它,如下所示: ```py >>> >>> >>> f = open("poem_2.txt", "w") >>> >>> f.write("When I think about myself, \n") # notice newline 27 >>> f.write("I almost laugh myself to death.\n") # notice newline 32 >>> >>> f.close() >>> >>> >>> f = open("poem_2.txt", "r") # open the file again >>> >>> data = f.read() # read the entire file >>> >>> data 'When I think about myself, \nI almost laugh myself to death.\n' >>> >>> print(data) When I think about myself, I almost laugh myself to death. >>> >>> ``` 您還可以使用`print()`函數將換行符附加到該行,如下所示: ```py >>> >>> f = open("poem_2.txt", "w") >>> >>> print("When I think about myself, ", file=f) >>> >>> print("I almost laugh myself to death.", file=f) >>> >>> f.close() >>> >>> >>> f = open("poem_2.txt", "r") # open the file again >>> >>> data = f.read() >>> >>> data 'When I think about myself, \nI almost laugh myself to death.\n' >>> >>> print(data) When I think about myself, I almost laugh myself to death. >>> >>> ``` 這是`writelines()`方法的示例。 ```py >>> >>> lines = [ ... "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod", ... "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam," ... "quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo", ... "consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse", ... "cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non", ... "proident, sunt in culpa qui officia deserunt mollit anim id est laborum." ... ] >>> >>> >>> f = open("lorem.txt", "w") >>> >>> f.writelines(lines) >>> >>> f.close() >>> ``` `writelines()`方法在內部調用`write()`方法。 ```py def writelines(self, lines): self._checkClosed() for line in lines: self.write(line) ``` 這是另一個以附加模式打開文件的示例。 ```py >>> >>> f = open("poem_2.txt", "a") >>> >>> f.write("\nAlone, all alone. Nobody, but nobody. Can make it out here alone.") 65 >>> f.close() >>> >>> data = open("poem_2.txt").read() >>> data 'When I think about myself, \nI almost laugh myself to death.\n\nAlone, all alone. Nobody, but nobody. Can make it out here alone.' >>> >>> print(data) When I think about myself, I almost laugh myself to death. Alone, all alone. Nobody, but nobody. Can make it out here alone. >>> ``` 假設文件`poem_2.txt`對于使用非常重要,并且我們不希望其被覆蓋。 為了防止在`x`模式下打開文件 ```py >>> >>> f = open("poem_2.txt", "x") Traceback (most recent call last): File "<stdin>", line 1, in <module> FileExistsError: [Errno 17] File exists: 'poem.txt' >>> ``` 如果`x`模式不存在,則僅打開該文件進行寫入。 ## 緩沖和刷新 * * * 緩沖是在將數據移到新位置之前臨時存儲數據的過程。 對于文件,數據不會立即寫入磁盤,而是存儲在緩沖存儲器中。 這樣做的基本原理是,將數據寫入磁盤需要花費時間,而不是將數據寫入物理內存。 想象一下,每當調用`write()`方法時一個程序正在寫入數據。 這樣的程序將非常慢。 當我們使用緩沖區時,僅當緩沖區已滿或調用`close()`方法時,才將數據寫入磁盤。 此過程稱為刷新輸出。 您也可以使用文件對象的`flush()`方法手動刷新輸出。 請注意,`flush()`僅將緩沖的數據保存到磁盤。 它不會關閉文件。 `open()`方法提供了一個可選的第三個參數來控制緩沖區。 要了解更多信息,請訪問官方文檔。 ## 讀寫二進制數據 * * * 通過將`b`附加到模式字符串來完成讀寫二進制文件。 在 Python 3 中,二進制數據使用稱為`bytes`的特殊類型表示。 `bytes`類型表示介于 0 和 255 之間的數字的不可變序列。 讓我們通過閱讀`poem.txt`文件來創建詩歌的二進制版本。 ```py >>> >>> binary_poem = bytes(open("poem.txt").read(), encoding="utf-8") >>> >>> binary_poem b'The caged bird sings\nwith a fearful trill\nof things unknown\nbut longed for still' >>> >>> >>> binary_poem[0] # ASCII value of character T 84 >>> binary_poem[1] # ASCII value of character h 104 >>> ``` 請注意,索引`bytes`對象將返回`int`。 讓我們將二進制詩寫在一個新文件中。 ```py >>> >>> f = open("binary_poem", "wb") >>> >>> f.write(binary_poem) 80 >>> >>> f.close() >>> ``` 現在,我們的二進制詩已寫入文件。 要讀取它,請以`rb`模式打開文件。 ```py >>> >>> f = open("binary_poem", "rb") >>> >>> data = f.read() >>> >>> data b'The caged bird sings\nwith a fearful trill\nof things unknown\nbut longed for still' >>> >>> print(data) b'The caged bird sings\nwith a fearful trill\nof things unknown\nbut longed for still' >>> >>> f.close() >>> ``` 重要的是要注意,在我們的情況下,二進制數據碰巧包含可打印的字符,例如字母,換行符等。但是,在大多數情況下并非如此。 這意味著對于二進制數據,由于文件中可能沒有換行符,因此我們無法可靠地使用`readline()`和文件對象(作為迭代器)來讀取文件的內容。 讀取二進制數據的最佳方法是使用`read()`方法分塊讀取它。 ```py >>> >>> # Just as with text files, you can read (or write) binary files in chunks. >>> >>> f = open("binary_poem", "rb") >>> >>> chunk = 200 >>> >>> while True: ... data = f.read(chunk) ... if not data: ... break ... print(data) ... b'The caged bird sings\nwith a fearful trill\nof things unknown\nbut longed for still' >>> >>> ``` ## 使用`fseek()`和`ftell()`的隨機訪問 * * * 在本文的前面,我們了解到打開文件時,系統將一個指針與它相關聯,該指針確定從哪個位置進行讀取或寫入。 到目前為止,我們已經線性地讀寫文件。 但是也可以在特定位置進行讀寫。 為此,文件對象提供了以下兩種方法: | 方法 | 描述 | | --- | --- | | `tell()` | 返回文件指針的當前位置。 | | `seek(offset, [whence=0])` | 將文件指針移動到給定的`offset`。 `offset`引用字節計數,`whence`確定`offset`將相對于文件指針移動的位置。 `whence`的默認值為 0,這意味著`offset`將使文件指針從文件的開頭移開。 如果`wherece`設置為`1`或`2`,則偏移量將分別將文件的指針從當前位置或文件的末尾移動。 | 現在讓我們舉一些例子。 ```py >>> >>> ###### binary poem at a glance ####### >>> >>> for i in open("binary_poem", "rb"): ... print(i) ... b'The caged bird sings\n' b'with a fearful trill\n' b'of things unknown\n' b'but longed for still' >>> >>> f.close() >>> >>> ##################################### >>> >>> f = open('binary_poem', 'rb') # open binary_poem file for reading >>> >>> f.tell() # initial position of the file pointer 0 >>> >>> f.read(5) # read 5 bytes b'The c' >>> >>> f.tell() 5 >>> ``` 讀取 5 個字符后,文件指針現在位于字符`a`(用字`caged`表示)。 因此,下一個讀取(或寫入)操作將從此處開始。 ```py >>> >>> >>> f.read() b'aged bird sings\nwith a fearful trill\nof things unknown\nbut longed for still' >>> >>> f.tell() 80 >>> >>> f.read() # EOF reached b'' >>> >>> f.tell() 80 >>> ``` 現在,我們已到達文件末尾。 此時,我們可以使用`fseek()`方法將文件指針后退到文件的開頭,如下所示: ```py >>> >>> f.seek(0) # rewind the file pointer to the beginning, same as seek(0, 0) 0 >>> >>> f.tell() 0 >>> ``` 文件指針現在位于文件的開頭。 從現在開始的所有讀取和寫入操作將從文件的開頭再次進行。 ```py >>> >>> f.read(14) # read the first 14 characters b'The caged bird' >>> >>> >>> f.tell() 14 >>> ``` 要將文件指針從當前位置從 12 個字節向前移動,請按以下步驟操作:`seek()`: ```py >>> >>> f.seek(12, 1) 26 >>> >>> f.tell() 26 >>> >>> ``` 文件指針現在位于字符`a`(在單詞`with`之后),因此將從此處進行讀取和寫入操作。 ```py >>> >>> >>> f.read(15) b'a fearful trill' >>> >>> ``` 我們還可以向后移動文件指針。 例如,以下對`seek()`的調用將文件指針從當前位置向后移 13 個字節。 ```py >>> >>> f.seek(-13, 1) 28 >>> >>> f.tell() 28 >>> >>> f.read(7) b'fearful' >>> ``` 假設我們要讀取文件的最后 16 個字節。 為此,將文件指針相對于文件末尾向后移 16 個字節。 ```py >>> >>> f.seek(-16, 2) 64 >>> >>> f.read() b'longed for still' >>> ``` `fseek()`的`whence`自變量的值在`os`模塊中也定義為常量。 | 值 | 常量 | | --- | --- | | `0` | `SEEK_SET` | | `1` | `SEEK_CUR` | | `2` | `SEEK_END` | ## `with`語句 * * * 使用`with`語句可使我們在完成處理后自動關閉文件。 其語法如下: ```py with expression as variable: ? ? # do operations on file here. ``` 必須像`for`循環一樣,將`with`語句內的語句縮進相等,否則將引發`SyntaxError`異常。 這是一個例子: ```py >>> >>> with open('poem.txt') as f: ... print(f.read()) # read the entire file ... The caged bird sings with a fearful trill of things unknown but longed for still >>> ``` * * * * * *
                  <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>

                              哎呀哎呀视频在线观看