Python3中的open函數

來源:互聯網
上載者:User

標籤:text   des   not   nta   sel   should   pen   spec   wrap   

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

    Open file and return a stream.  Raise IOError upon failure.

#開啟檔案並返回一個流?失敗則拋出IOError異常

mode:

    ========= ===============================================================

    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)

    ========= ===============================================================

mode不使用參數預設是'rt',‘w’寫入模式,會覆蓋原來全部的內容(會建立檔案),‘x’建立一個新的檔案,並寫入內容如果檔案存在會‘FileExistsError’,‘a’在檔案末尾追加內容,‘b’二進位模式,‘+’更新磁碟檔案(讀寫),‘U’棄用

參數有a和w會建立不存在的檔案


buffering:

    buffering is an optional integer used to set the buffering policy.

    Pass 0 to switch buffering off (only allowed in binary mode), 1 to select

    line buffering (only usable in text mode), and an integer > 1 to indicate

    the size of a fixed-size chunk buffer.  When no buffering argument is

    given, the default buffering policy works as follows:

* Binary files are buffered in fixed-size chunks; the size of the buffer

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

    

    * "Interactive" text files (files for which isatty() returns True)

      use line buffering.  Other text files use the policy described above

      for binary files.

0 只能用在二進位模式

1 行緩衝

>1 則使用給定的值做緩衝大小

*在沒有給出參數的情況下,二進位檔案的大小有底層裝置“block size”決定,可以通過‘io.DEFAULT_BUFFER_SIZE’擷取,在很多系統中這個值的大小為4096或者8192位元組

*文字檔則採用行緩衝

encoding:

encoding is the name of the encoding used to decode or encode the

    file. This should only be used in text mode. The default encoding is

    platform dependent, but any encoding supported by Python can be

    passed.  See the codecs module for the list of supported encodings.

encoding是檔案的解碼或者編碼方式,只能用於文字模式,預設的編碼方式依賴於平台,任何python能夠支援編碼都可以在python中使用,可以查看編碼模組


errors:

errors is an optional string that specifies how encoding errors are to

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

    errors. (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是一個可選的參數,並且不能用於二進位模式,如果出現編碼錯誤會排出ValueError錯誤,或者使用‘ignoe’忽略,可通過查看codecs.codec擷取錯誤編碼字串


newline:

newline controls how universal newlines works (it only applies to text

    mode). It can be None, '', '\n', '\r', and '\r\n'.  It works as

    follows:

    

    * On input, if newline is None, universal newlines mode is

      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and

      these are translated into '\n' before being returned to the

      caller. If it is '', universal newline mode is enabled, but line

      endings are returned to the caller untranslated. If it has any of

      the other legal values, input lines are only terminated by the given

      string, and the line ending is returned to the caller untranslated.

    

    * On output, if newline is None, any '\n' characters written are

      translated to the system default line separator, os.linesep. If

      newline is '' or '\n', no translation takes place. If newline is any

      of the other legal values, any '\n' characters written are translated

      to the given string.

換行控制,參數可以用None, '', '\n', '\r', and '\r\n'(只能用於文字模式)

*輸入時,

如果參數為None,那麼分行符號啟用,結尾可以是'\n', '\r', or '\r\n',並且這些控制符都會編碼為'\n'。

如果是''分行符號模式啟用,但是行位的分行符號在返回調用時將不會被編碼。

如果給出其他有效參數,返回調用時將會使用指定的參數

*輸出時,

如果參數為None,任何‘\n’將會編碼成系統預設的分隔字元

如果參數為‘’或者'\n',將不會編碼

如果參數為其他有效值,'\n'將會編碼成給定的值


closefd:

If closefd is False, the underlying file descriptor will be kept open

    when the file is closed. This does not work when a file name is given

    and must be True in that case.

當檔案關閉時,如果closefd為False,底層檔案描述仍然是開啟,設定為True底層檔案描述同時也會關閉。


opener:

A custom opener can be used by passing a callable as *opener*. The

    underlying file descriptor for the file object is then obtained by

    calling *opener* with (*file*, *flags*). *opener* must return an open

    file descriptor (passing os.open as *opener* results in functionality

    similar to passing None).

可以通過調用*opener*來自訂opener,底層檔案是通過調用*opener*, *file*, *flags*來擷取描述。*opener*必須返回一個開啟的檔案描述。os.open作為*opener*的返回結果類似於通過None。


 open() returns a file object whose type depends on the mode, and

    through which the standard file operations such as reading and writing

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

    a file in a binary mode, the returned class varies: in read binary

    mode, it returns a BufferedReader; in write binary and append binary

    modes, it returns a BufferedWriter, and in read/write mode, it returns

    a BufferedRandom.

    

    It is also possible to use a string or bytearray as a file for both

    reading and writing. For strings StringIO can be used like a file

    opened in a text mode, and for bytes a BytesIO can be used like a file

    opened in a binary mode.


:~/Code$ cat opentestpythonis a open testthis is ababcedfdfcdagdagkasggasdgagaggfdnsdnhsdfosdfigsodfnh****

使用r+的結果

eg.

>>> f = open('opentest', 'r+')>>> f.write('1111')4>>> f.write('2222')4>>> f.write('3333')4>>> f.close()


再次查看opentest內容

:~/Code$ cat opentest111122223333pen testthis is ababcedfdfcdagdagkasggasdgagaggfdnsdnhsdfosdfigsodfnh****

使用r+,指標在開頭,會覆蓋掉原位置原有的內容

Python3中的open函數

聯繫我們

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