"WITH" Attachment in Python

It turns out that “c” is a fun word to search on the Internet.

Does anyone know what a transaction with an attachment with operators in python is?
I was tracking a very slippery error in the script that I wrote, and I suspect that this is because I am doing this:

with open(file1) as fsock1:
    with open(file2, 'a') as fsock2:
        fstring1 = fsock1.read()
        fstring2 = fsock2.read()

Python fires when I try read()from fsock2. When checking in the debugger, this happens because it considers the file to be empty. This is not a concern, except for the fact that the execution of the same code in inter-operator debugging not in an expression withshows me that the file is really filled with text ...

I am going to proceed from the assumption that at the moment nested expressions withare no-no, but if someone who knows more has a different opinion, I would like to hear it.

+5
source share
5 answers

I found a solution in a python document. You can watch this

If you are using python 3.1+, you can use it like this:

with open(file1) as fsock1, open(file2, 'a') as fsock2:
    fstring1 = fsock1.read()
    fstring2 = fsock2.read()

This way you avoid unnecessary indentation.

+5
source

AFAIK you cannot read a file opened with the add mode 'a'.

+6
source

, , .

, , . , , .

with :

with open(file1) as f:
    with open(file2, 'r') as g:   # Read, not append.
        fstring1 = f.read()
        fstring2 = g.read()

, contextlib.nested, , . , :

with contextlib.nested(open(file1, "wt"), open(file2)) as (f_out, f_in):
   ...

. , 2 (, ), 1, . .

+3

with - , file2 append, .

with, - contextlib.nested. , (, , , ), with, , .

+1

"", "+" Google .

0

All Articles