-1
The goal is to replace each occurrence of the word "secret" with "XXXX" in the Crypto.txt file.
My code:
def crypto(arquivo):
#palavras = []
with open(arquivo,"r") as crypto:
data = crypto.read()
data =data.replace("secret","XXX")
with open(arquivo,"w") as crypto:
crypto.write(data)
crypto("crypto.txt")
The code above works perfectly, but I kept thinking: I opened the file in read-only mode "r", then recorded in "date" the text of the file with overwriting, but needed to open the file again, only in "w" mode. Why not already open the file in write mode ("r+"or "w+") and thus not need to open the file twice? I did so:
def crypto(arquivo):
#palavras = []
with open(arquivo,"w+") as crypto:
data = crypto.read()
data =data.replace("secret","XXX")
#print(data)
crypto.write(data)
crypto("crypto.txt")
Unfortunately, neither using "r+" mode nor "w+" code works the same way as the first. What is happening?
With "r+", it creates a copy of the text inside the file replacing "secret" with "XXX" but I get the duplicate text... With "w+" I end up with an empty file...
:I don’t understand, because Crypto.write(date) is inside with...
– Ed S
With "r+", it creates a copy of the text inside the file replacing "secret" with "XXX" but I get the duplicate text... With "w+" I end up with an empty file...
– Ed S
I’m not sure, but I think that date right there that second with will be
None
. Fordata
only exists in the scope of the first with. I usually never specify those letters... It’s hard to need that. No need to split into 2 withs By default it opens "rw", I think (if not specified). https://www.tutorialspoint.com/cprogramming/c_file_io.htm– wkrueger
That answer is almost all wrong. The
with
does not generate an isolated context, it instantiates a context manager, which transfers the control responsibility of the current context to an object. When that object is the result of the functionopen
, the file will be opened when entering thewith
and closed on exit; all variables created within thewith
belong to his own scope, is not isolated.– Woss
And it is almost always necessary to specify the opening mode of a file, unless you always use read-only,
'r'
, which is the default mode. I talked about these modes in What is the difference between r+ and w+ modes in Python?– Woss
Isolated where the outside variables cannot access the variables from within the context, and the inside variables can access the outside variables. As in all contexts...
– wkrueger
and there it was just open as rw and delete that second line of with. No need to open the file twice...
– wkrueger