gdo*_*371 0 python xml unicode utf-8
我正在尝试使用以下语句将一些数据写出到Unicode XML文件中:
filepath = 'G:\Kodi EPG\ChannelGuide.xml'
with open(filepath, "w", encoding = 'UTF-8') as xml_file:
xml_file.write(file_blanker)
xml_file.close
Run Code Online (Sandbox Code Playgroud)
...但是出现以下错误:
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
Run Code Online (Sandbox Code Playgroud)
我已经将其视为一个问题的可接受答案,但这是针对Python 3xx的。版本2的语法是否略有不同?
谢谢
是的,Python2的语法不同-关于encoding参数。
Python2 open说明:
open(name[, mode[, buffering]])
Run Code Online (Sandbox Code Playgroud)
Python3 open说明:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Run Code Online (Sandbox Code Playgroud)
如您所见,在Python 2.7 open中不接受encoding参数,因此类型错误。
但是,您可以使用内置io模块打开文件。这将允许您指定编码,并且还提供与Python3的兼容性。例如,
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)
Run Code Online (Sandbox Code Playgroud)
请注意,使用with语句时不必显式关闭文件。