令人讨厌的编码问题

时间:2014-11-29 23:10:31

标签: python windows python-2.7 encoding character

我检查了这个解决方案,找不到任何有用的问题。 当我打开文件并在文件中写入内容时,我必须使用"ş,Ş,ğ,Ğ,ü,Ü,ö,Ö,ç,Ç"之类的土耳其语字符。但这是我的问题:

with open("file1.txt","a","utf-8-sig") as f:
    f.write(u"ŞşşĞĞğğğüüüÜÜİİİii")

我每次都会收到此错误:

  with open("file1.txt","a","utf-8-sig") as f:
TypeError: an integer is required

真的很烦人。我尝试了一切。

这就是我启动Python脚本的方式:

# -*- coding: cp1254 -*-
#!/usr/bin/env python
# -*-coding:utf-8-*-
from __future__ import division
import locale
locale.setlocale(locale.LC_ALL, '')

我无法对文件进行编码。如果我试试这个:

with open("file1.txt","a",encoding="utf-8-sig") as f:

我收到了这个错误:

TypeError: 'encoding' is an invalid keyword argument for this function

在Pyhon3x中我可以做什么编码?

1 个答案:

答案 0 :(得分:9)

在Python 2中,open() function不带encoding个参数。第三个参数是缓冲选项。

您似乎与 Python 3版本混淆。如果是这样,请改用io.open()

import io

with io.open("file1.txt", "a", encoding="utf-8-sig") as f:

在Python 3中,io.open()函数替换了Python 2中的版本。

您可能想要研究Unicode和Python:

相关问题