Open multiple files with "with open"

3

You can open more than one file in a program with

with open("meutexto.txt", "r") as f:

I did not find anything about it (or did not look right). I know you can do it differently:

var = open("meutexto.txt", "r")
var_dois = open("meu_segundo_texto.txt", "r")
var_tres = open("meu_terceiro_texto", "r")

But I would like to know if it's possible with with open

    
asked by anonymous 04.09.2017 / 11:55

1 answer

4

It is possible, yes, from version 2.7 of Python. See:

What is with in Python?

The syntax for multiple expressions in with is to separate them with a comma:

with EXPR1 as VAR1, EXPR2 as VAR2:
    BLOCK

That is, to open multiple files, just do:

with open("texto_1.txt") as var_1, open("texto_2.txt") as var_2:
    # código

When exiting the block of with , all files will be properly closed.

    
04.09.2017 / 13:15