Open multiple files with "with open"

Asked

Viewed 649 times

3

It is possible to open more than one file in a program with

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

I didn’t find anything about it (or didn’t look hard enough). I know it’s possible to do otherwise:

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

But I wonder if it’s possible with the with open

1 answer

4


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

What’s with no Python for?

The syntax for various 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

On leaving the block of with, all files will be properly closed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.