简体   繁体   English

将所有输出写入文件(Python)

[英]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. 我有这段代码应该生成所有可能的数字组合,并将它们存储在名为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. 这里的问题是,当我转到文本文件时,它仅显示9999,而不显示0000到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. 您的f.write不在循环内,因此它只会发生一次。

You probably want the open() before the loop, and your f.write in the loop (indented, same as print ). 您可能希望在循环之前使用open() ,并在循环中使用f.write(缩进,与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 . 到时候你打开文件,并在循环结束后写的话), i已经被设置为在循环的最后结果,这就是为什么你只得到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 : 这是更Pythonic的方式:

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 ... Python照顾了这里的一切...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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