4

I am trying to create and save KeePass entries using pykeepass and saving a .txt file as an attachment. However I get a type-error:

Traceback (most recent call last):
  File "c:\Users\Simplicissimus\Documents\coding\directory\attachment.py", line 15, in <module>
    entry.add_attachment('attachment.txt', f.read())
    ~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Simplicissimus\AppData\Local\Programs\Python\Python313\Lib\site-packages\pykeepass\entry.py", line 163, in add_attachment
    E.Key(filename),
    ~~~~~^^^^^^^^^^
  File "src\\lxml\\builder.py", line 219, in lxml.builder.ElementMaker.__call__
TypeError: bad argument type: bytes(b'Lorem Ipsum bla bla bla\r\n')
(base) PS C:\Users\Simplicissimus\Documents\coding\directory> 

My minimal reproducible example is:

from pykeepass import PyKeePass

kp = PyKeePass('testDatabase.kdbx', password='passwort')

generalGroup = kp.find_groups(name='General',first=True)
entry = kp.add_entry(
    generalGroup,  
    title='title',  
    username='username',
    password= 'password',
)

with open('loremipsum.txt', 'rb') as f:
    entry.add_attachment('attachment.txt', f.read())

kp.save()

(All files are in the same directory, the file loremipsum.txt contains the line: "Lorem Impsum bla bla bla")

How do I have to convert the file content of a .txt-file to Bytes?

I am using the pykeepass Version: 4.1.0.post1, Keepass Version 2.58 and Python 3.13.

2
  • always put full error message because there are other useful information. Commented Apr 20 at 21:00
  • link shows that it needs text, not bytes - so you should open as r, not rb Commented Apr 20 at 21:02

1 Answer 1

2

I can't test it but examples on page pykeepass show

# add attachment data to the db
>>> binary_id = kp.add_binary(b'Hello world')

>>> kp.binaries
[b'Hello world']

# add attachment reference to entry
>>> a = e.add_attachment(binary_id, 'hello.txt')

So maybe it needs first add it as add_binary() and later attache it to entry

with open('loremipsum.txt', 'rb') as f:
    binary_id = kp.add_binary(f.read())

    a = entry.add_attachment(binary_id, 'attachment.txt')
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! I oversaw this and thought it meant the file-id of the os.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.