Home > Mobile >  Writing strings to a text file in python
Writing strings to a text file in python

Time:07-28

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.

CodePudding user response:

You need to .close() file or use with statement.

This is including some optimizations:

import string
import random
import os

alphabet = string.ascii_lowercase   string.ascii_uppercase   string.digits
with open("Passphrases2.txt", "w") as pass_file:
    for _ in range(1000):
        st = "".join(random.choice(alphabet) for i in range(random.randint(8, 16)))
        print(st)
        pass_file.write("%s\n" % p)

os.chmod("Passphrases2.txt", 0o777)

CodePudding user response:

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)

CodePudding user response:

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.

CodePudding user response:

You need to close the file in the end

  • Related