python-3.x - 在python中将字符串写入文本文件

标签 python-3.x file-handling

我使用以下代码在 python 中生成一些随机字符串:

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)

我希望将这些字符串存储在与 python 代码相同目录下的文本文件中。

当我执行这段代码时,会创建一个名为 Passphrases2.txt 的文件,但在第一次执行时它是空的。

当我第二次执行相同的代码时,文件会更新为第一次执行时生成的字符串,然后在第三次运行时,它会更新为第二次执行时生成的字符串,依此类推.我无法弄清楚为什么会这样。

最佳答案

您需要.close() 文件或使用with 语句。

这包括一些优化:

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)

关于python-3.x - 在python中将字符串写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73133227/

相关文章:

multithreading - 使用STDOUT(屏幕)与常规文件的性能

python-3.x - Selenium 和异步

python - 尝试在下载的 Cython 目录中安装 Cython : no setup. py

python - 在 Windows 上的 python 代码中无法捕获 KeyboardInterrupt

c++ - 以下代码是单个文件中的文件读/写。但是此代码无法创建文件

java - 从数组列表写入文件,反之亦然

c - 在 C 文件中写入矩阵的内容

python-3.x - 从 ._sparsetools 导入 csr_tocsc、csr_tobsr、csr_count_blocks、\ImportError : DLL load failed: The specified module could not be found

python - 为什么这个 lambda 函数在 else 语句中表现得很奇怪?

c - 为什么我的追加函数不再写入文件