Python "Attributeerror: __exit__" problem

Asked

Viewed 499 times

5

In a group, I asked them to give me tips on some program to test my knowledge. He told me to create a program that reads a file called "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

That’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__

1 answer

7


We’re missing a open on the line:

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

Thus, ('arquive.txt', 'wb') is just a tuple. The mistake is because the with expects an object with __enter__ and __exit__, what a tuple does not have (but the return value of open, yes).

The correct code, therefore, is:

with open('arquive.txt', 'wb') as non:
  • xD was over 2:30h trying and nothing. Vlw guy!

  • @Breno if the answer solved your problem mark it as correct. How and why to accept an answer?

  • @Guilhermenascimento Sorry, it’s that I thought there was no way, I clicked on the up arrow and could not.

Browser other questions tagged

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