"AttributeError: __exit__" problem in Python

5

In a group, I asked them to give me tips on a program to test my knowledge. He told me to create a program that reads a file named "arquive.txt" and manages files CHAR and STAGE , with the file like this:

[CHAR]
Exemplo = C:/Users/Usuário/Desktop/New Folder/file1.char
[STAGE]
Exemplo2 = C:/Users/Usuário/Desktop/New Folder/file2.stage

Here's what I did:

import ConfigParser as CP
cfg  = CP.RawConfigParser()

'''
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Olá, bom dia, esse é meu novo programa.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'''
h = open('arquive.txt', 'r+')
if h.readlines() == []:
    h.close()
    cfg.add_section("CHAR")
    cfg.add_section("STAGE")
    with open('arquive.txt', 'wb') as fl:
        cfg.write(fl)
    with open('arquive.txt', 'r') as fg:
        print fg.readlines()

class Char(object):
    def __init__(self, nome, caminho):
        self.nome = nome
        self.caminho = caminho
    def addChar(self):
        g = open('arquive.txt', 'r')
        cfg.readfp(g)
        cfg.set("CHAR", self.nome, self.caminho)
        g.close()
        with ('arquive.txt', 'wb') as non:
            cfg.write(non)

inserir = raw_input("Nome do Char: ")
inserir2 = raw_input("Caminho do Char: ")

char = Char(inserir, inserir2)
char.addChar()

But when I run the program, the error appears:

Traceback (most recent call last):
File "/root/arquivo.py", line 35, in <module>
char.addChar()
File "/root/arquivo.py", line 28, in addChar
with ('arquive.txt', 'wb') as non:
AttributeError: __exit__
    
asked by anonymous 04.12.2016 / 01:58

1 answer

7

A open is missing from the line:

with ('arquive.txt', 'wb') as non:

In this way, ('arquive.txt', 'wb') is just a tuple. The error is because with expects an object with __enter__ and __exit__ , which a tuple does not have (but the return value of open , yes).

The correct code, therefore, is:

with open('arquive.txt', 'wb') as non:
    
04.12.2016 / 02:23