Difference | Python's open () and with open () as

 

https://www.jianshu.com/p/34d7fff5fc51

1, open () method


 

Meaning: Open a file and returns a file object, if the file can not be opened, it will throw OSError. Finally, be sure to call the close () method to ensure close the file object.

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

Parameters (generally uses a file, mode and encoding)

  • file: Required , file path (relative or absolute path).
  • mode: Optional, the file open mode
  • buffering: a buffer
  • encoding: utf8 general use
  • errors: error level
  • newline: distinguish line break
  • closefd: Incoming file parameter types
  • opener:

mode parameter

the way Explanation
'r' Read mode (default)
'w' Write mode, it will clear the file open
'x' Write mode, create a new file, if the file already exists it will error.
'a' Add mode, files can only be written to the write end of the file, can not read
'b' Binary mode (text mode by default, if you want to use binary mode, with 'b')
't' Text mode (default)
'+' Open a file is updated (read and write)
'U' Universal wrap mode (not recommended)

 

 

 




 

 

 

 

note:

(1) r +: can read and write, the file is not empty when opened, can be written anywhere in the file. At the beginning of the default file, the file will be overwritten.

(2) a +: can read and write, the file is not empty when opened, only the end of the file is written.

(3) using the open () method, and finally close the file object must ensure that calls close () method. The reason: When we write a file, the operating system often do not immediately write data to disk, but cached into memory, free time and then slowly write. Only call the close () method, the operating system was written to ensure that the data is not written to disk at the same time to release all the resources. Forget to call close () the consequences of data may be written only part of the disk, and the rest is lost.

 

 

 

2、with open() as 用法


 
Under normal circumstances, I want to open a file and ensure that the file will be closed. we need
try:
    f = open('C:/path/to/file', 'r')
    # do something about f
finally:
    if f:
        f.close()

 

 Use with ... as ... to ensure that the file must be closed.
with open('/path/to/file', 'r') as f:
    f.read()
    ...

 

 


 

Guess you like

Origin www.cnblogs.com/zwt20120701/p/12105322.html