MythicMango
MythicMango

Reputation: 62

Python how to write bytes in a .txt file

I have a program that puts your string into bytes, and writes it on a new line every time. For some reason, it doesn't do that. It gives me:

File "c:/InstaBots/password.py", line 44, in store
    file.write(encrypted_data + '\n')
TypeError: can't concat str to bytes

Here is the code:

with open("passwords.txt", "rb") as file:
    file_data = file.read()
    encrypted_data = f.encrypt(file_data)
    decoded = encrypted_data.decode()
    print(encrypted_data)
with open("passwords.txt", "wb") as file:
    file.write(encrypted_data + '\n')

Any ideas why it won't convert? I took out the '/n', assuming it would be that, but then it rewrites over itself everytime I run the program. If that is the problem, how would I write bytes on a new line?

Upvotes: 0

Views: 884

Answers (2)

jizhihaoSAMA
jizhihaoSAMA

Reputation: 12672

Your code in the end should be :

with open("passwords.txt", "ab") as file:
    file.write(b'\n'+encrypted_data + b'\n')

Upvotes: 1

Barmar
Barmar

Reputation: 781004

You need to convert \n to bytes.

file.write(encrypted_data + bytes('\n'))

Upvotes: 1

Related Questions