Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/jsf/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 写入文件,然后保存一个_Python - Fatal编程技术网

Python 写入文件,然后保存一个

Python 写入文件,然后保存一个,python,Python,我想知道为什么当我试图将代币保存到save时总是保存第一个代币 #!/usr/bin/python import random import string count = 1 while count <= 5: t = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation key = str(''.join(random.sample(t,33)))

我想知道为什么当我试图将代币保存到save时总是保存第一个代币

#!/usr/bin/python
import random
import string

count = 1
while count <= 5:
    t = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation
    key = str(''.join(random.sample(t,33)))
    with open('keys','w') as keys:
        keys.write(key)
    count += 1
#/usr/bin/python
随机输入
导入字符串
计数=1
而计数
#/usr/bin/python
随机输入
导入字符串
计数=1
以open('key','w')作为键:

计数时,您需要将文件追加到文件中,而不是每次写入文件,即在
open
as中使用“a”而不是“w”-

#!/usr/bin/python
import random
import string

count = 1
while count <= 5:
    t = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation
    key = str(''.join(random.sample(t,33)))
    with open('keys','a') as keys:
        keys.write(key)
    count += 1
#/usr/bin/python
随机输入
导入字符串
计数=1

每次打开
文件时,都要进行计数,同时删除文件中的所有内容。我不知道你想做什么,所以我帮不了你更多。我想把我的5轮while保存到我的文件中,但只保存第一轮,只保存最后一轮。如果您想这样做,您可以初始化一个列表,在每个循环中附加它,并将其保存在循环外的
keys
文件中。您真的希望所有输出都像这样位于一行吗?或者您希望将每个
字符串写入单独的一行吗?我会修复它,但例如,如果添加了前5个键,我如何检查同一文件中的哪些键是新键?
#!/usr/bin/python
import random
import string

count = 1
while count <= 5:
    t = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation
    key = str(''.join(random.sample(t,33)))
    with open('keys','a') as keys:
        keys.write(key)
    count += 1