如何在Python中将列表写入文件

2024-10-01 00:29:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序可以把文件的内容加密成密文。我要写的是一个密文列表。在

我需要帮助的代码部分是:

for char in encryptFile:
    cipherTextList = []
    if char == (" "):
        print(" ",end=" ")
    else:
        cipherText = (ord(char)) + offsetFactor
    if cipherText > 126:
        cipherText = cipherText - 94
        cipherText = (chr(cipherText))
        cipherTextList.append(cipherText)
        for cipherText in cipherTextList:
                print (cipherText,end=" ")
    with open ("newCipherFile.txt","w") as cFile:
        cFile.writelines(cipherTextList)

整个程序运行平稳,但是新密码文件.txt“里面只有一个字。在

我想这和空列表“cipherTextList=[]”的位置有关,但是我尝试过将这个列表从for循环移到函数中,但是当我打印它时,打印密文的部分处于一个无限循环中,并且反复打印普通文本。在

任何帮助都很好。在


Tags: 文件in程序txt内容列表forif
2条回答

使用("newCipherFile.txt","a")代替("newCipherFile.txt","w")a表示追加,w表示覆盖。在

您一直用w覆盖打开的文件,因此只看到最后的值,请使用a附加:

 with open("newCipherFile.txt","a") as cFile:

或者一个更好的主意,在循环外打开一次:

^{pr2}$

相关问题 更多 >