I want to close a python file and then open it again

Asked

Viewed 967 times

0

Do not call the variables name. When the program tries to open the file after closed, it does not open.

from time import strftime
n = 2
cl = 2
abrir_arquivo = open("C:/Users/lucas/Documents/Documento.rtf", 'w')
while(1):
    m = 2**n - 1
    v = 1
    simples =  int(m / 2 + 1)
    o = 0
    h = strftime('%D %H:%M:%S')
    for c in range(0, simples):
        if m % v == 0:
            o = o + 1
        v = v + 1
        if o == 3:
            break
    if o < 3:
        print('Esse número mercene é primo: %i. Ele é o M%i. Ele foi elevado à %i.'%(m,cl, n))
        print(strftime('%D:%H:%M:%S'),'   ', h)
        **abrir_arquivo
        abrir_arquivo.write('Esse número mercene é primo: %i. Ele é o M%i. Ele foi elevado à %i.'%(m,cl, n))
        abrir_arquivo.close()**
        cl = cl + 1
        n = n + 1
  • I think your code was missing in the question, but why do you want to close and then open the same file?

  • It is because I want that when I close the program it saves what has already been processed

  • I will still make modifications to the code so that it takes the data that was saved in the file and continues processing from that point

2 answers

1

To open a file and insert a content at the end of the existing content, you must pass the flag to+(append) in the open(), instead of the flag w, which only opens the file for writing.

Example:

file = open('arquivo.txt', 'a')
file.write('Hello World!')
file.close()

The text Hello World! is inserted at the end of txt file., and does not overwrite existing content.

0

I don’t understand the efficiency of what Voce is doing, but Voce can declare a function for this

def abre_arquivo():
    arquivo = open("C:/Users/lucas/Documents/Documento.rtf", 'w')

And call her when you need to record something.

if o < 3:
    print('Esse número mercene é primo: %i. Ele é o M%i. Ele foi elevado à %i.'%(m,cl, n))
    print(strftime('%D:%H:%M:%S'),'   ', h)
    abre_arquivo()
    arquivo.write('Esse número mercene é primo: %i. Ele é o M%i. Ele foi elevado à %i.'%(m,cl, n))
    arquivo.close()

The only problem is that Voce will have to structure your program differently the most patron saint

The only observation I wanted to make for Oce, is that the moment Python receives the write it writes the line in the text file. So technically speaking, Voce is only complicating a simple thing :/

Browser other questions tagged

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