Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

python - Encrypt a word line by line

I have this script that opens a file and encrypts it to base64 and then saves the encryption in file output.txt, but there is a problem, it collects the words in a file in one line, I want to print each word in a file and save each word on a new line and not in one line.

For example:
Where is my problem in my code?

import base64

with open("out.txt","r") as file:
    count = 0

    while True: 
        count += 1

        # Get next line from file 
        line = file.read()

        # if line is empty 
        # end of file is reached 
        if not line: 
            break
        message_bytes = line.encode('ascii')
        base64_bytes = base64.b64encode(message_bytes)
        base64_message = base64_bytes.decode('ascii')
        print(base64_message.format(count, line.strip()), file=open("output.txt", "a"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You encode your file like this:

import base64

with open("input.txt","rb") as in_file:
    with open("output.txt", "wb") as out_file:
        for line in in_file:
            out_file.write(base64.b64encode(line) + b"
")

You can open both input and output files with "rb" (read bytes) and "wb" (write bytes), so you don't have to do the ascii encoding yourself. With for line in input you go over each line of the input file one by one, so that you can encode them one at a time. The last important part is the + b" " at the end, which adds a new line for every line of the input file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...