jwodder / javaproperties

Python library for reading & writing Java .properties files
MIT License
30 stars 10 forks source link

dump_xml () method, TypeError: write() argument must be str, not bytes #9

Closed tkang007 closed 3 years ago

tkang007 commented 4 years ago

Hello,

I would like to report an abnormal case on dump_xml method with below code and output. Please let me know if I am misusing in system default, UTF8 locale environment.

test code

import javaproperties
import traceback

properties = {"key": "value", "host:port": "127.0.0.1:80", "snowman": "☃", "goat": "🐐"}

with open('text.properties', 'w') as wf:
    javaproperties.dump(properties, wf, sort_keys=True)

try:
    with open('xml.properties', 'w') as wf:
        javaproperties.dump_xml(properties, wf, sort_keys=True)
except Exception as exc:
    traceback.print_exc()

with open('xml.properties', 'w') as wf:
    print(javaproperties.dumps_xml(properties, sort_keys=True), file=wf)    

with open('text.properties', 'r') as rf:
    print('text.properties:')
    print(javaproperties.load(rf))

with open('xml.properties', 'r') as rf:
    print('xml.properties:')
    print(javaproperties.load_xml(rf))

test ouptut

raceback (most recent call last):
  File "jp.py", line 11, in <module>
    javaproperties.dump_xml(properties, wf, sort_keys=True)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/javaproperties/xmlprops.py", line 109, in dump_xml
    print('<?xml version="1.0" encoding={0} standalone="no"?>'
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/codecs.py", line 378, in write
    self.stream.write(data)
TypeError: write() argument must be str, not bytes
text.properties:
{'goat': '🐐', 'host:port': '127.0.0.1:80', 'key': 'value', 'snowman': '☃'}
xml.properties:
{'goat': '🐐', 'host:port': '127.0.0.1:80', 'key': 'value', 'snowman': '☃'}

javaproperties version

Name: javaproperties
Version: 0.7.0
Summary: Read & write Java .properties files
Home-page: https://github.com/jwodder/javaproperties
Author: John Thorvald Wodder II
Author-email: javaproperties@varonathe.org
License: MIT
Location: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages
Requires: six
Required-by: javaproperties-cli

Thanks, TK

jwodder commented 4 years ago

As stated in the documentation, the second argument to dump_xml() must be a binary filehandle, but you are passing a text filehandle. In Python 3, you create a binary filehandle by including a b in the open() mode, i.e., by writing:

with open('xml.properties', 'wb') as wf:
                   # Add this ^
        javaproperties.dump_xml(properties, wf, sort_keys=True)