我有一组存储变量的文本文件,我试图将其读入Python。只要变量不包含任何法语字符,例如é,ç等。下面这段代码效果很好:
#!/usr/bin/python
import imp
def getVarFromFile(filename):
f=open (filename, 'rt')
global data
data = imp.load_source('data', " ", f)
f.close()
return()
def main():
getVarFromFile('test.txt')
print data.Title
print data.Language
print data.Summary
return()
if __name__ == "__main__":
main()
示例输出:
me@mypc:$ ./readVar.py
Monsieur Flaubert
French
A few lines of text.
但是,当文本文件包含法语字符时,例如:
Title = "Monsieur Flaubert"
Language = "Français"
Summary = "Quelques lignes de texte en Français. é à etc."
我收到以下错误,我无法找到解决方案:
Traceback (most recent call last):
File "./tag.py", line 30, in <module>
main()
File "./tag.py", line 22, in main
getVarFromFile('test.txt')
File "./tag.py", line 15, in getVarFromFile
data = imp.load_source('data', " ", f)
File " ", line 2
SyntaxError: Non-ASCII character '\xc3' in file on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
如何处理法语(utf-8)字符? 感谢您对这位Python学习者的考虑和帮助。