Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List - Fatal编程技术网

如何用python将列表写入文件

如何用python将列表写入文件,python,list,Python,List,我有一个程序可以将文件内容加密成密文。我希望程序将列表中的密文写入文件 我需要帮助的代码部分是: for char in encryptFile: cipherTextList = [] if char == (" "): print(" ",end=" ") else: cipherText = (ord(char)) + offsetFactor if cipherText > 126: cipherTex

我有一个程序可以将文件内容加密成密文。我希望程序将列表中的密文写入文件

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

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)
整个程序运行顺利,但是名为“newCipherFile.txt”的文件中只有一个字符

我认为这与空列表“cipherTextList=[]”的位置有关,但是我尝试将此列表从for循环移动到函数中,但是当我打印它时,打印密文的部分处于无限循环中,并反复打印正常文本


任何帮助都会很有用。

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

 with open("newCipherFile.txt","a") as cFile:
或者一个更好的主意,在循环之外打开它一次:

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

使用
(“newCipherFile.txt”,“a”)
代替
(“newCipherFile.txt”,“w”)
a
用于追加,而
w
用于重写。

可能重复@iTzAlexF,不用担心,第二个是更好的选择,因为您不需要重复打开文件。