简体   繁体   English

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

[英]How to write a list to a file in python

I have a program that encrypts the contents of a file into cipher text. 我有一个程序,将文件的内容加密为密文。 I want the program to write the ciphertext, that Is in a list, to a file. 我希望程序将列表中的密文写入文件。

The part of my code I need help with is: 我需要帮助的部分代码是:

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)

The whole program runs smoothly, however the file that is called "newCipherFile.txt" only has one character in it. 整个程序运行顺利,但是名为“newCipherFile.txt”的文件只有一个字符。

I think this has something to do with the location of the empty list "cipherTextList = []", however I have tried moving this list out of the for loop, into the function, but when I print it the part that prints the ciphertext is in an infinite loop and prints the normal text over and over again. 我认为这与空列表“cipherTextList = []”的位置有关,但是我已经尝试将这个列表从for循环中移出到函数中,但是当我打印它时,打印密文的部分是在无限循环中,一遍又一遍地打印普通文本。

Any help would be lovely. 任何帮助都很可爱。

You keep overwriting opening the file with w so you only ever see the very last values, use a to append: 你继续用w覆盖打开文件,所以你只看到最后的值,使用a追加:

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

Or a better idea so to open it outside the loop once: 或者更好的想法,以便在循环外打开一次:

with open("newCipherFile.txt","w") as cFile:
    for char in encryptFile:
        cipherTextList = []
        ............

Use ("newCipherFile.txt","a") instead of ("newCipherFile.txt","w") . 使用("newCipherFile.txt","a")代替("newCipherFile.txt","w") a is for append and w is for over-write. a用于追加, w用于覆盖。

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

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