简体   繁体   中英

Writing all outputs to a file (Python)

I have this code that should generate all possible combinations of digits and store them in a text file called Passwords4.txt. The issue here is that when I go to the text file it just shows 9999 instead of showing the numbers from 0000 to 9999.

import itertools
lst = itertools.product('0123456789', repeat=4) #Last part is equal to the password lenght
for i in lst:
    print ''.join(i)
f = open('Passwords4.txt', 'w')
f.write(str(''.join(i)) +'\n')
f.close()

Can someone explain what should I do?

Your f.write is not inside the loop, so it only happens once.

You probably want the open() before the loop, and your f.write in the loop (indented, same as print ).

Re:

for i in lst:
    print ''.join(i)
f = open('Passwords4.txt', 'w')
f.write(str(''.join(i)) +'\n')

By the time you open the file and write to it after the loop is finished), i has already been set to just the last result of the loop and that's why you're only getting 9999 .

A fix is to do the writes within the loop, with something like:

import itertools
lst = itertools.product('0123456789', repeat=4)
f = open('Passwords4.txt', 'w')
for i in lst:
    f.write(''. join(i) + '\n')
f.close()

This is the more Pythonic way of doing :

import itertools
lst = itertools.product('0123456789', repeat=4) #Last part is equal to the password lenght
with open('Passwords4.txt', 'w') as f:
    for i in lst:
        print ''.join(i)
        f.write(str(''.join(i)) +'\n')

Python takes care of everything here ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM