Why must we add the suffix as? to use with open, in python

Doesn"t

as mean renaming the file? does it have any special meaning here?

as

as

Mar.20,2021

print out their types and find that the types are inconsistent.

In [5]: import json 
In [6]: num = [1,2,3,4,5,6,7]
In [7]: file_1 = 'first.json'
In [8]: with open(file_1,'w') as joe:
   ...:     print(type(joe))
   ...:     json.dump(num, joe)
   ...:     
<class '_io.TextIOWrapper'>
In [14]: import json 
In [15]: num = [1,2,3,4,5,6,7]
In [16]: file_1 = 'first.json'
In [17]: with open(file_1, 'w'):
    ...:     print(type(file_1))
    ...:     json.dump(num, file_1)
    ...:     
    ...:     
    ...:     
<class 'str'>
AttributeError: 'str' object has no attribute 'write'

the second section of code
uses the open method to open the file, but still uses the direct string object file_1, which is equivalent to no open.
is equivalent to the following code:

import json
file_1 = 'first.json'
json.dump(num, file_1)

and the string itself is not written to this method, so the error is: AttributeError: 'str' object has no attribute' write'

if you don't want with, you can assign the open object to f = open (file_1,'w')

.

as is not renaming the original file.
as represents the opened file handle. For example, f = open (file_1,'w') , the one after as is equivalent to this f variable. With is used because with is a context manager that automatically closes files. There is no need to call f.close ().


with as is context manager , implemented using Python's magic method .
refer to python/sub-2" rel=" nofollow noreferrer "> context Manager -python/28" rel= "nofollow noreferrer" > Magic method

Menu