简体   繁体   中英

Creating a unicode XML file in Python 2.7.1

I am trying to write some data out into a unicode XML file with the following statement:

filepath = 'G:\Kodi EPG\ChannelGuide.xml'
with open(filepath, "w", encoding = 'UTF-8') as xml_file:
    xml_file.write(file_blanker)
xml_file.close

...but am getting the following error:

Traceback (most recent call last):
  File "G:\Python27\Kodi\Sky TV Guide Scraper.py", line 35, in <module>
    class tv_guide:
  File "G:\Python27\Kodi\Sky TV Guide Scraper.py", line 47, in tv_guide
    with open(filepath, "w", encoding = 'UTF-8') as xml_file:
TypeError: 'encoding' is an invalid keyword argument for this function

I have seen this given as an accepted answer on here to a question, but that was for Python 3xx. Is the syntax slightly different for version 2?

Thanks

Yes, the syntax is different for Python2 - regarding the encoding argument.

Python2 open description:

open(name[, mode[, buffering]])

Python3 open description:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

As you can see, in Python 2.7 open doesn't accept the encoding argument, hence the Type Error.

However you can use the built-in io module to open your files. This would allow you to specify the encoding, and also provide compatibility with Python3. For example,

import io

filepath = r'G:\Kodi EPG\ChannelGuide.xml'
with io.open(filepath, "w", encoding = 'UTF-8') as xml_file:
    xml_file.write(file_blanker)

Note that you don't have to explicitly close your files when using the the with statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM