Open files that will be shared between various functions, inside or outside the functions?

0

Next, I'm doing a program that I'm going to split between the function module and the interface, and I need to use files in that project (and I can not use classes), so I need to use those files between several functions, they will write in them, others will read only, and so on. Here's a piece of code:

arqProfessores = open("arqProfessores.txt","r+")
arqDisciplinas = open("arqDisciplinas.txt","r+")
arqAlunos = open("arqAlunos.txt","r+")
arqTurmas = open("arqTurmas.txt","r+")


def addProfessor(cpf, nome, departamento):
    if cpf not in arqProfessores:
    dicProfessor = {"Nome":nome, "Cpf":cpf, "Departamento":departamento}
    arqProfessores = open("arqProfessores.txt","a")
    arqProfessores.write(dicProfessor)
    arqProfessores.close()
    print("Professor cadastrado com sucesso.")
else:
    print("Erro de cadastro.\nEste professor já está cadastrado no 
sistema.")


def consultarProfessor(cpf):
    arqProfessores = open("arqProfessores.txt","r")
    if cpf in arqProfessores:
        dicProfessor = arqProfessores.read(cpf)          #definindo uma 
variavel para a chave do dicionario de professores
        for chave,elem in dicProfessor.items():
            print(chave + ": " + str(elem))
        arqProfessores.close()
else:
    print("Este professor não é funcionário desta faculdade.")

(the formatting is not like this) Anyway, for example, it has a function that I have that I have to write to the file without deleting what is already written so the "a" in the file, but up there I opened as "r +", sorry for the ignorance, but I I'm very lazy when it comes to file: / What do you recommend doing?

    
asked by anonymous 25.06.2017 / 17:46

1 answer

0

If I had to build this kind of program, I would have the function get a file-like object, and would use a 'context manager' (the with ) in the program's main features to make the code more "readable". An example of what I mean:

def funcao(par1, par2, par3, arquivo):
    # fazer_coisas
    arquivo.write()


def funcao2(par1, par2, par3, arquivo):
    # fazer outras coisas
    arquivo.write()


def main():

    try:
        # abra os arquivos com o modo que se precisar
        with open('arquivo1', 'rw') as a, open('arq2', 'rw') as b:
            # coisas
            funcao(2, 3, 4, a)
            funcao2(2, 3, 4, b)
            # outras coisas

    except IOError as e:
        print('Operation failed: {erro}'.format(erro=e.strerror))

Be aware that with with you do not need to close the file. The .__exit__ method, which is executed when the program exits from with , takes care of this. Part of this answer I relied on here >.

    
26.06.2017 / 21:50