我从这样的文本文件中创建了一个列表:
plain_text = open((input_filename), 'r')
characters = list(plain_text.read())
但是我无法做反向并将列表写入新的文本文件。我试图通过使用for循环但是得到错误来做到这一点。
ciphertext = open('chipher text', 'w')
for x in characters:
ciphertext.write(characters[x])
错误:
TypeError: list indices must be integers, not str
为什么我收到错误以及将列表写入文本文件的正确方法是什么?
答案 0 :(得分:0)
试试这个
output = ''.join(characters)
f = open('myfile','w')
f.write(output)
f.close()
修改强> 使用编解码器模块写入带编码的文件
import codecs
output = ''.join(characters)
f = codecs.open("myfile", "w", "utf-8", "replace")
f.write(output)
希望这会有所帮助