Reputation: 145
I am generating some random strings in python using the following code:
import string
import random
import os
passphrases = []
pass_file = open("Passphrases2.txt","w")
os.chmod("Passphrases2.txt",0o777)
for _ in range(100):
st = "".join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for i in range(random.randint(8,16)))
passphrases.append(st)
print(st)
for p in passphrases:
pass_file.write("\n"%p)
I want these strings to be stored in a text file in the same directory as the python code.
When I execute this code, a file named Passphrases2.txt
gets created but it is empty in the first execution.
When I execute the same code for the second time, the file gets updated with the strings that were generated during the first execution, then on running the third time, it gets updated with the strings generated in the second execution and so on. I am unable to figure out why this is happening.
Upvotes: 2
Views: 147
Reputation: 805
You need to .close()
file or use with
statement.
This is including some optimizations:
import os
from random import choice, randint
import string
alphabet = string.ascii_lowercase + string.ascii_uppercase + string.digits
with open("Passphrases2.txt", "w") as pass_file:
for _ in range(1000):
st = "".join(choice(alphabet) for i in range(randint(8, 16)))
print(st)
pass_file.write(f"{st}\n")
os.chmod("Passphrases2.txt", 0o777)
Upvotes: 4
Reputation: 3555
It's because you are missing pass_file.close()
at the end to properly close the file handle after finishing to write. Without properly closing, the write to file was not fully flushed and saved. It's like you are typing something in Notepad but have not yet hit the save button.
Then on the 2nd run, pass_file = open("Passphrases2.txt","w")
, reopening the file handle will close the previous handle; this will act like pass_file.close()
for the previous run and thus you are seeing previous data on 2nd run and so on.
You may add pass_file.close()
after the last for loop or use the Python with
statement to ensure file handle open is being closed properly after it is done.
Upvotes: 3
Reputation: 154
import string
import random
import os
passphrases = []
for _ in range(100):
st = "".join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for i in range(random.randint(8,16)))
passphrases.append(st)
print(st)
with open("Passphrases2.txt","w") as pass_file:
for p in passphrases:
pass_file.write("%s\n" %p)
Upvotes: 3