尽管我的打印工作,但我无法写入文件

时间:2016-02-09 09:41:57

标签: python

我要写入文件的信息打印得非常好,如下所示:

  

你想要这个名字是什么? sample1.txt

     

{97 / A2 / H- + 9H6 / 7 + 8H63 @ / H89> H6981H + 19TH98 / H90H> 29 = / HA29H2 + = H + H6 + 8 / H + 8.H + 8-3 / 8是氢; H = 23 / 6.H98H + H = 2 / 60H + 8.H5 //:= H + H = 5388CH8 + 1H + 8.H + H1      

这是加密邮件。

但是,当我检查文件时,没有内容。代码如下:

file = file_contents()
total = key_offset()
encrypted = ''
character_number = 0
length = len(file)

while character_number < length:
    char = file[character_number]

    ordinal = ord(char)
    encrypted_ordinal = ordinal + total

    if encrypted_ordinal > 126:
        encrypted_ordinal = encrypted_ordinal - 94

    encrypted_char = chr(encrypted_ordinal)
    encrypted = encrypted + encrypted_char
    character_number += 1

    if character_number == length:              
        encrypt_file = input("What do you want the name to be? ")
        file1 = open(encrypt_file, "w")
        file1.write(str(encrypted))
        print(encrypted)
        print("This is the encrypted message.")
        the_menu()

当我尝试解密时,明显的错误是没有文件内容。如果我需要提供任何东西,请发表评论。

1 个答案:

答案 0 :(得分:-1)

我通常用于阅读和写入文件。

with open('encrypt_file.txt', "wb") as file1:
    file1.write(str(encrypted))

它自动关闭文件,虽然它被认为是错误的python代码(但不是坏的Cpython代码)