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

Asked

Viewed 46 times

1

Next, I’m making a program that I’m going to divide between the function module and the interface, and I need to use files in this project (and I can’t use classes), it turns out I need to use these files between various functions, some that will write to them, others that will just read, etc. Here a piece of the 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.")

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

1 answer

0

If I had to build this type of program, I would cause the function to receive a file type object, and use a 'context manager' (the with) in the main features of the program to make the code more "feasible". 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 the with do not need to close the file. The method itself .__exit__, that is executed when the program leaves the with takes care of it. Part of that answer I based myself here.

Browser other questions tagged

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