How to use python files

Asked

Viewed 226 times

-1

I am still finishing a program as work of Project I and I have a lot of difficulty in the part of files. I am unable to insert an array into the file. Does anyone know how to do this?

The program is about Einstein’s game, and has to have the following requirements on the file part:

Option 3: Print a report with history in a text file plays (filled words and positions) in addition to the updated matrix and of the score (number of hits), for each registered player.

The Archive must also contain the average number of moves between players to achieve success (complete the array), as well, which player completed the array with the fewest number of moves and the one with the highest number of moves.

After completion of the report, inform the user the name of the generated text file.

The program for now looks like this: (deletes what is not needed for files, as the result matrix)

arqParcial=open("parcial.txt","w")
arqParcial.write("Relatório de Jogadas: \n")
arqParcial.write("Coluna / Alteração\n")
arqParcial.close()
matriz=[]
for i in range (6):
    linha=['-']*6
    matriz.append(linha)
matriz[0][0]=':D'
matriz[0][1]='Casa 1'
matriz[0][2]='Casa 2'
matriz[0][3]='Casa 3'
matriz[0][4]='Casa 4'
matriz[0][5]='Casa 5'
matriz[1][0]= '1.Cor'
matriz[2][0]= '2.Nacionalidade'
matriz[3][0]= '3.Bebida'
matriz[4][0]= '4.Cigarro'
matriz[5][0]= '5.Animal'
for i in range(6):
    print(matriz[i])

print('') 
print('Dicas: \nO Norueguês vive na primeira casa. \nO Inglês vive na casa Vermelha. \nO Sueco tem Cachorros como animais de estimação. \nO Dinamarquês bebe Chá. \nA casa Verde fica do lado esquerdo da casa Branca. \nO homem que vive na casa Verde bebe Café. \nO homem que fuma Pall Mall cria Pássaros. \nO homem que vive na casa Amarela fuma Dunhill. \nO homem que vive na casa do meio bebe Leite. \nO homem que fuma Blends vive ao lado do que tem Gatos. \nO homem que cria Cavalos vive ao lado do que fuma Dunhill. \nO homem que fuma BlueMaster bebe Cerveja. \nO Alemão fuma Prince. \nO Norueguês vive ao lado da casa Azul. \nO homem que fuma Blends é vizinho do que bebe Água.')
print('')
print('OBS: Digite tudo como indicado acima, incluindo os acentos.')
print('')
linha=input('Digite o número correspondente a linha que deseja alterar(1.Cor; 2.Nacionalidade; 3.Bebida; 4.Cigarro; 5.Aninal) ou Desisto ou Acabei: ')
linha=linha.upper()


while linha != 'ACABEI' and linha != 'DESISTO':
    linha=int(linha)
    coluna=int(input('Digite o número correspondente a coluna que deseja alterar (Casa 1; Casa 2; Casa 3; Casa 4; Casa 5: '))
    novo=input('Digite a alteração: ')
    novo=novo.lower()
    matriz[linha][coluna]=novo
    visu=input('Deseja visualizar a tabela (S ou N)? ')
    visu=visu.upper()
    with open("parcial.txt", "a") as arqParcial:
        arqParcial.writelines(str(coluna)+ "  /  ")
        arqParcial.writelines(str(novo)+"\n")
        for i in range(6):
            arqParcial.writelines(matriz[i])
    if visu == 'S':
        for i in range(6):
            print(matriz[i])
 

But in that part:

for i in range(6):
            arqParcial.writelines(matriz[i])

Makes a mistake. Can someone help me?

1 answer

2

At first glance, there is no problem in the program that would justify an error in the line you indicate - but there are several other problems in building the program, which will make it not work as planned, and may lead to errors in this or other places.

Already uqe you had a problem in the method writelines I begin there: this method is used when you want to pass an iterable - for example, a list of strings - to be saved consecutively in the file. By coincidence it works when you pass a single string as well - because Python considers a string as a single letter string interbox - that is, when you write: arqParcial.writelines(str(coluna)+ " / ")Python solves the expression between parentheses, which results in a string of type "1 / " - and writelines writes in the file the characters "1", "", "/" and " ", as if each one were a line. In such cases, the best is to use the method write of the file, no writelines.

On the line you indicate, the use of writelines would be correct - but it will only work if each element of the list passed to the file is a string. If any element is different from a string (such as a number, or None), ioo writelines does not auto-convert to string and gives error - so the exact error message is important.

Now, looking at the program, it seems to be a program made in Python 3.x - since you handle the value returned from input as a string on the line new=new.Lower() ` - and in this case all matrix elements would be strings. Shouldn’t give error - although I’m not sure if it will write what you want in the file.

Another thing is that in Python normalmetne do not use as much the for with range how do you do: the for already returns each element of a sequence - so except the first for where you create your matrix, all others can be exchanged for something like:

for i in range(6):
    print(matriz[i])

for

for linha in matriz:
    print (linha)

There is no need for an auxiliary index variable.

As I said, these are some tips - but without the error message you have, there’s no telling why the program stops on that line specifically.

Browser other questions tagged

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