python File 内置 open()方法(打开文件)
生活随笔
收集整理的這篇文章主要介紹了
python File 内置 open()方法(打开文件)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- From builtins.py
- Dontla 20191030
- Dontla 20200422
From builtins.py
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open"""Open file and return a stream. Raise IOError upon failure.打開文件并返回流。 失敗時拋出IOError異常。file is either a text or byte string giving the name (and the pathif the file isn't in the current working directory) of the file tobe opened or an integer file descriptor of the file to bewrapped. (If a file descriptor is given, it is closed when thereturned I/O object is closed, unless closefd is set to False.)file是一個文本或字節字符串,給出了要打開的文件的名稱(如果文件不在當前工作目錄中,則給出了路徑)或要包裝的文件的整數文件描述符。 (如果給出了文件描述符,則除非將closefd設置為False,否則當關閉返回的I / O對象時,它將關閉。)mode is an optional string that specifies the mode in which the fileis opened. It defaults to 'r' which means open for reading in textmode. Other common values are 'w' for writing (truncating the file ifit already exists), 'x' for creating and writing to a new file, and'a' for appending (which on some Unix systems, means that all writesappend to the end of the file regardless of the current seek position).In text mode, if encoding is not specified the encoding used is platformdependent: locale.getpreferredencoding(False) is called to get thecurrent locale encoding. (For reading and writing raw bytes use binarymode and leave encoding unspecified.) The available modes are:mode是一個可選字符串,用于指定打開文件的模式。 默認為“ r”,這意味著可以在文本模式下閱讀。 其他通用值是用于寫入的“ w”(如果文件已經存在,則將其內容清空),用于創建和寫入新文件的“ x”,以及用于附加的“ a”(在某些Unix系統上,這意味著所有寫入都附加到 不論當前搜尋位置在文件末尾)。 在文本模式下,如果未指定編碼,則使用的編碼取決于平臺:調用locale.getpreferredencoding(False)以獲取當前的語言環境編碼。 (要讀取和寫入原始字節,請使用二進制模式,同時不用指定編碼。)可用模式為:========= ===============================================================Character Meaning--------- ---------------------------------------------------------------'r' open for reading (default) 打開讀模式(默認)'w' open for writing, truncating the file first 打開寫模式,先截斷文件(可能就是不能邊寫邊讀)'x' create a new file and open it for writing 創建一個新文件并打開以進行寫入'a' open for writing, appending to the end of the file if it exists 打開進行寫入,如果存在內容則追加到文件末尾'b' binary mode 二進制模式't' text mode (default) 文字模式(默認)'+' open a disk file for updating (reading and writing) 打開磁盤文件以進行更新(讀取和寫入)'U' universal newline mode 通用換行模式 (deprecated 強烈不建議)========= ===============================================================The default mode is 'rt' (open for reading text). For binary randomaccess, the mode 'w+b' opens and truncates the file to 0 bytes, while'r+b' opens the file without truncation. The 'x' mode implies 'w' andraises an `FileExistsError` if the file already exists.默認模式是“ rt”(打開以閱讀文本)。 對于二進制隨機訪問,模式“ w + b”將打開并將文件截斷為0字節,而模式“ r + b”將打開文件而不會截斷。“ x”模式包含“ w”的功能并且,如果文件已經存在,則引發“ FileExistsError”。(所以就是,如果穩健存在時,用‘w’就不會引發異常)Python distinguishes between files opened in binary and text modes,even when the underlying operating system doesn't. Files opened inbinary mode (appending 'b' to the mode argument) return contents asbytes objects without any decoding. In text mode (the default, or when't' is appended to the mode argument), the contents of the file arereturned as strings, the bytes having been first decoded using aplatform-dependent encoding or using the specified encoding if given.Python區分以二進制和文本模式打開的文件,即使底層操作系統沒有。 以二進制模式打開的文件(在mode參數后面添加“ b”)以字節對象形式返回內容,而無需進行任何解碼。 在文本模式下(默認值,或在模式參數后附加't'),文件內容以字符串形式返回,首先使用與平臺有關的編碼或指定的編碼(如果給定的話)對字節進行解碼。'U' mode is deprecated and will raise an exception in future versionsof Python. It has no effect in Python 3. Use newline to controluniversal newlines mode.不建議使用“ U”模式,它將在將來的Python版本中引發異常。 它在Python 3中無效。使用換行符控制通用換行符模式。buffering is an optional integer used to set the buffering policy.Pass 0 to switch buffering off (only allowed in binary mode), 1 to selectline buffering (only usable in text mode), and an integer > 1 to indicatethe size of a fixed-size chunk buffer. When no buffering argument isgiven, the default buffering policy works as follows:buffering是用于設置緩沖策略的可選整數。 傳遞0以關閉緩沖(僅在二進制模式下允許),傳遞1以選擇行緩沖(僅在文本模式下可用),并傳遞大于1的整數以指示固定大小的塊緩沖區的大小。 如果未指定任何緩沖參數,則默認的緩沖策略如下:* Binary files are buffered in fixed-size chunks; the size of the bufferis chosen using a heuristic trying to determine the underlying device's"block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.On many systems, the buffer will typically be 4096 or 8192 bytes long.* 二進制文件以固定大小的塊緩沖; 緩沖區的大小是通過試探法來確定底層設備的“塊大小”,然后回退到io.DEFAULT_BUFFER_SIZE上進行選擇的。在許多系統上,緩沖區的長度通常為4096或8192字節。 * "Interactive" text files (files for which isatty() returns True)use line buffering. Other text files use the policy described abovefor binary files.* “交互式”文本文件(isatty()返回True的文件)使用行緩沖。 其他文本文件將上述策略用于二進制文件。encoding is the name of the encoding used to decode or encode thefile. This should only be used in text mode. The default encoding isplatform dependent, but any encoding supported by Python can bepassed. See the codecs module for the list of supported encodings.* encoding是用于解碼或編碼文件的編碼的名稱。 僅應在文本模式下使用。 默認編碼取決于平臺,但是可以支持Python支持的任何編碼。 有關支持的編碼列表,請參見編解碼器模塊。errors is an optional string that specifies how encoding errors are tobe handled---this argument should not be used in binary mode. Pass'strict' to raise a ValueError exception if there is an encoding error(the default of None has the same effect), or pass 'ignore' to ignoreerrors. (Note that ignoring encoding errors can lead to data loss.)See the documentation for codecs.register or run 'help(codecs.Codec)'for a list of the permitted encoding error strings.errors是一個可選字符串,它指定如何處理編碼錯誤---不應在二進制模式下使用此參數。 如果存在編碼錯誤(默認值為None具有相同的效果),則傳遞“ strict”以引發ValueError異常,或傳遞“ ignore”以忽略錯誤。 (請注意,忽略編碼錯誤可能會導致數據丟失。)請參閱codecs.register的文檔,或運行“ help(codecs.Codec)”以獲取允許的編碼錯誤字符串列表。newline controls how universal newlines works (it only applies to textmode). It can be None, '', '\n', '\r', and '\r\n'. It works asfollows:newline控制通用換行符的工作方式(僅適用于文本模式)。 可以是“無”,“”,“ \ n”,“ \ r”和“ \ r \ n”。 它的工作方式如下* On input, if newline is None, universal newlines mode isenabled. Lines in the input can end in '\n', '\r', or '\r\n', andthese are translated into '\n' before being returned to thecaller. If it is '', universal newline mode is enabled, but lineendings are returned to the caller untranslated. If it has any ofthe other legal values, input lines are only terminated by the givenstring, and the line ending is returned to the caller untranslated.*在輸入時,如果換行符為None,則啟用通用換行符模式。 輸入中的行可以以'\ n','\ r'或'\ r \ n'結尾,在返回給調用者之前,這些行會轉換為'\ n'。 如果為”,則啟用通用換行模式,但行結尾不翻譯就返回給呼叫者。 如果它具有任何其他合法值,則輸入行僅由給定的字符串終止,并且該行的末尾未經轉換返回給調用方。* On output, if newline is None, any '\n' characters written aretranslated to the system default line separator, os.linesep. Ifnewline is '' or '\n', no translation takes place. If newline is anyof the other legal values, any '\n' characters written are translatedto the given string.*在輸出中,如果換行符為None,則任何寫入的'\ n'字符都將轉換為系統默認的行分隔符os.linesep。 如果換行符是''或'\ n',則不會進行翻譯。 如果換行符是其他任何合法值,則將寫入的所有“ \ n”字符轉換為給定的字符串。If closefd is False, the underlying file descriptor will be kept openwhen the file is closed. This does not work when a file name is givenand must be True in that case.如果closefd為False,則關閉文件時基礎文件描述符將保持打開狀態。 給定文件名時,此方法不起作用,在這種情況下必須為True。A custom opener can be used by passing a callable as *opener*. Theunderlying file descriptor for the file object is then obtained bycalling *opener* with (*file*, *flags*). *opener* must return an openfile descriptor (passing os.open as *opener* results in functionalitysimilar to passing None).可以通過將可調用對象傳遞為* opener *來使用自定義的opener。 然后通過使用(* file *,* flags *)調用* opener *獲得文件對象的基礎文件描述符。 * opener *必須返回打開文件描述符(將os.open作為* opener *傳遞,其功能類似于傳遞None)。open() returns a file object whose type depends on the mode, andthrough which the standard file operations such as reading and writingare performed. When open() is used to open a file in a text mode ('w','r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to opena file in a binary mode, the returned class varies: in read binarymode, it returns a BufferedReader; in write binary and append binarymodes, it returns a BufferedWriter, and in read/write mode, it returnsa BufferedRandom.open()返回一個文件對象,其類型取決于模式,并通過該文件對象執行諸如讀寫之類的標準文件操作。 當使用open()以文本模式(“ w”,“ r”,“ wt”,“ rt”等)打開文件時,它將返回TextIOWrapper。 當用于以二進制模式打開文件時,返回的類有所不同:在讀取二進制模式下,它返回BufferedReader; 在寫二進制和追加二進制模式下,它返回BufferedWriter;在讀/寫模式下,它返回BufferedRandom。It is also possible to use a string or bytearray as a file for bothreading and writing. For strings StringIO can be used like a fileopened in a text mode, and for bytes a BytesIO can be used like a fileopened in a binary mode.也可以使用字符串或字節數組作為文件進行讀取和寫入。 對于字符串,可以將StringIO用作以文本模式打開的文件,而對于字節,可以將BytesIO用作以二進制模式打開的文件。"""passDontla 20191030
貌似在使用’w+'模式對文件進行寫讀操作的時候(先寫后讀),讀不出來東西。。。空白的
引用文章:day-2 python 文件讀寫模式r,r+,w,w+,a,a+的區別
Dontla 20200422
在看LabelImg代碼的時候,發現程序會使用
def read(filename, default=None):try:with open(filename, 'rb') as f:return f.read()except:return default二進制模式來讀取圖片數據
但是顯示卻是16進制的
總結
以上是生活随笔為你收集整理的python File 内置 open()方法(打开文件)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python File write()方
- 下一篇: python pycharm如何全局(整