How to print a. txt file in Python

Asked

Viewed 1,559 times

1

I try to print that part of my work into a file. txt (code below), but I can’t, because at the time of giving Run in the file that whole part comes out blank: inserir a descrição da imagem aqui

It is worth mentioning that even leaving blank, the file is saved anyway, but all the fields that were to be made come out blank: inserir a descrição da imagem aqui

If you want the full code to get something: http://pastebin.com/x8k5HgsZ

import sys
sys.stdout=open("trab.txt","w")

print("DADOS DE " + str(nome1).upper())
dados1 = registro()
print("Matrícula : " + dados1[0] + "\nTelefone: " + dados1[1] + "\nEndereço: " + dados1[2] +
      "\n 1º Nota [ " + str(vet_nota1[0]) + " ]   2º Nota[ " + str(vet_nota1[1]) + " ]")

print("\n")
print("DADOS DE " + str(nome2).upper())
dados2 = registro()
print("Matrícula : " + dados2[0] + "\nTelefone: " + dados2[1] + "\nEndereço: " + dados2[2] +
      "\n  1º Nota [ " + str(vet_nota2[0]) + " ]   2º Nota[ " + str(vet_nota2[1]) + " ]")

sys.stdout.close()

1 answer

0


Try this, it’s another approach to writing in the file:

#Salvando em txt
text = ''
text += "DADOS DE " + str(nome1).upper()
dados1 = registro()
text += "\nMatrícula : " + dados1[0] + "\nTelefone: " + dados1[1] + "\nEndereço: " + dados1[2]+ "\n 1º Nota [ " + str(vet_nota1[0]) + " ]   2º Nota[ " + str(vet_nota1[1]) + " ]\n"

text += "\nDADOS DE " + str(nome2).upper()
dados2 = registro()
text += "\nMatrícula : " + dados2[0] + "\nTelefone: " + dados2[1] + "\nEndereço: " + dados2[2]+ "\n  1º Nota [ " + str(vet_nota2[0]) + " ]   2º Nota[ " + str(vet_nota2[1]) + " ]"
with open('trab.txt', 'w') as f:
    f.write(text)
print(text)
  • Gives an error of: in <module> f.write(text) Valueerror: I/O Operation on closed file.

  • 1

    @Kennethanderson this is because the indentation is not correct, f.write(..) should be at the level of the previous lines (as I put), within the with

  • Now it worked, but a problem happened: It’s as if the lines were all together, without breaking lines. What do you think I can do to have lines broken in the final result?

  • 1

    @Kennethanderson the breaks are there both in the file and in the print. Copy what I put

Browser other questions tagged

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