`
kanpiaoxue
  • 浏览: 1781312 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

python add utf-8 character set

 
阅读更多

python 3.*以前的版本,打印汉字等亚洲字符,需要在.py文件的开头额外添加编码信息。这里我就是简单的写了一个添加utf-8编码的工具方法,方便自己使用。其实,在 pyDev IDE里面,可以给每个文件定义开头的。我的博客里面有。这里就给出一个可以遍历指定目录里面所有.py的文件,没有添加编码的,全部添加编码。

 

 

#-*-coding:utf-8-*-

'''
Created on 2012-4-22

@author: kanpiaoxue
'''
from string import strip
import os

class PythonUtil(object):
    UTF8_STRING = '#-*-coding:utf-8-*-'
    def __init__(self):
        pass
    def addAddUtf8(self, inputFile):
        needUtf8ListFiles = self.needUtf8(inputFile)
        count = len(needUtf8ListFiles)
        if count > 0:
            for tmpFile in needUtf8ListFiles:
                print tmpFile, ' need to add ', self.UTF8_STRING
                readFile = None
                writeFile = None
                try:
                    readFile = open(tmpFile, 'r')
                    lines = readFile.readlines()
                    lines.insert(0, self.UTF8_STRING + '\n')
                    writeFile = open(tmpFile, 'w')
                    writeFile.writelines(lines)
                    print 'add ', self.UTF8_STRING, ' to ', tmpFile
                finally:
                    if readFile is not None:
                        readFile.close()
                    if writeFile is not None:
                        writeFile.flush()
                        writeFile.close()
        print '\n-------------- result report begin --------------'
        if count > 0:
            print 'add ', self.UTF8_STRING, ' to ', count, ' files successfully.'
        else:
            print 'there are not any files needing to add ', self.UTF8_STRING
        print '--------------  result report end  --------------\n'
    
    def needUtf8(self, inputFile):
        needUtf8ListFiles = []
        if not os.path.isdir(inputFile):
            print '[', inputFile, '] is not a valid folder. Please check it.'
            return needUtf8ListFiles
        for root, dirs, files in os.walk(inputFile):
            for name in files:
                f = os.path.join(root, name)
                if f.endswith('.py') :
                    tmpFile = None
                    try:
                        tmpFile = open(f, 'r')
                        lines = tmpFile.readlines()
                        if len(lines) > 0:
                            if strip(lines[0]) != self.UTF8_STRING:
                                needUtf8ListFiles.append(f)
                        else:
                            needUtf8ListFiles.append(f)
                    finally:
                        if tmpFile is not None:
                            tmpFile.close()
        return needUtf8ListFiles
                    

if __name__ == '__main__':
    f = r'E:\workspace_python'
    pythonUtil = PythonUtil()
    pythonUtil.addAddUtf8(f)

    
分享到:
评论

相关推荐

    LeetCode最全代码

    393 | [UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [C++](./C++/utf-8-validation.cpp) [Python](./Python/utf-8-validation.py) | _O(n)_ | _O(1)_ | Medium | | 401 | [Binary Watch]...

    openstack queens 简易快速安装 完成版(不建议新手介入)

    内容如下:[mysqld] bind-address = 10.32.24.255 default-storage-engine = innodb innodb_file_per_table = on max_connections = 4096 collation-server = utf8_general_ci character-set-server = utf8。...

    python3.6.5参考手册 chm

    PEP 529: Change Windows filesystem encoding to UTF-8 PEP 528: Change Windows console encoding to UTF-8 PEP 520: Preserving Class Attribute Definition Order PEP 468: Preserving Keyword Argument ...

    python-常用单词及语法_1681366872966.doc

    Python是一种广泛使用的高级编程语言,以其简洁明了的语法和强大的功能著称。本文将深入探讨Python中的常用词汇和语法。 一、交互式环境与print输出 Python的交互式环境允许程序员快速测试代码片段,而`print`是...

    华为OD机试C卷- 启动多任务排序(Java & JS & Python & C).md-私信看全套OD代码及解析

    graph = {task: set(deps) for task, deps in dependencies.items()} no_deps = deque(task for task, deps in graph.items() if not deps) order = [] while no_deps: current = no_deps.popleft() order....

    phython语言0基础学习课程

    - 修改数据库:`ALTER DATABASE database_name CHARACTER SET utf8 COLLATE utf8_general_ci;` - 删除数据库:`DROP DATABASE database_name;` - 创建表:`CREATE TABLE table_name (column1 datatype, column2 ...

    Python采用Django制作简易的知乎日报API

    DEFAULT_CHARSET = 'utf-8' ``` 3. **数据库字符集设置**:登录到数据库后执行以下命令,确保数据库的字符集设置为`utf8`。 ```sql SET character_set_client = utf8; SET character_set_connection = utf8; ...

    Python常用英文单词

    Python常用英文单词 Python是一种广泛使用的编程语言,了解Python常用英文单词对于提高编程效率和理解代码至关重要。下面是Python常用英文单词的总结: 一、交互式环境与print输出 * print:打印/输出 * coding:...

    mysql安装手册

    default-character-set=utf8 [mysqld] default-storage-engine=INNODB character_set_server=utf8 ``` - 复制`mysql.server`到`/etc/init.d/mysql`: ```bash cp /usr/local/mysql/support-files/mysql....

    Zabbix部署

    mysql> create database zabbix character set utf8 collate utf8_bin; mysql> grant all on zabbix.* to 'zabbix'@'%' identified by 'zabbix'; mysql> flush privileges; ``` 初始化数据库 我们可以使用以下命令...

    XML Processing with Perl, Python, and PHP (2002).pdf

    Python, for example, runs on MacOS, Unix, Windows and PalmOS. Rebol runs on even more. AppleScript is a standard part of every MacOS revision since 8.0 and is even included in MacOS X. Perl is ...

    Python英语单词整理.pdf

    Python是一种广泛使用的高级编程语言,以其易读性强、语法简洁而受到欢迎。在学习Python时,掌握一些核心的英语词汇是必要的。以下是一些关键概念的详细解释: 1. **interpreter**:Python解释器是执行Python代码的...

    Python 常用英文单词

    Python是一种广泛使用的高级编程语言,以其易读性、简洁的语法和丰富的库支持而闻名。在学习Python时,了解一些常用的英文单词对于理解和编写代码至关重要。以下是一些关键概念的详细解释: 一、交互式环境与print...

    Mysql练习10.1

    ALTER DATABASE database1 CHARACTER SET utf8; ``` 这将将 `database1` 数据库的编码修改为 UTF-8。 6. 查看数据库结构 查看数据库结构是通过 `DESC` 语句实现的。例如: ```sql DESC database1.student; ``` 这...

    Linux上安装Mysql及简单的使用详解

    若需要指定编码,例如UTF-8: ``` create database test1 default character set utf8 collate utf8_general_ci; ``` 7. 删除数据库: ``` drop database database_name; ``` 8. 插入数据到表中: ``` insert into...

    sql的相关命令及重要语句归纳

    CREATE DATABASE python27 CHARACTER SET utf8; ``` 查看创建数据库的完整语句: ```sql SHOW CREATE DATABASE python27; ``` 切换到某个数据库: ```sql USE python27; ``` 删除数据库: ```sql DROP DATABASE ...

    JavaC组蓝桥杯107道历年真题.pdf

    Set<Character> set = new HashSet(); for (int i = 0; i (); i++) { set.add(s.charAt(i)); } return set.size() == 10; } ``` **答案解析:** - 通过暴力法或Set集合方法,可以得出维纳当时的年龄是18岁。 ...

    python编程必备英语(全)

    ### Python编程必备英语知识点详解 #### 一、交互式环境与 print 输出 1. **print**: 打印或输出信息到屏幕。例如:`print("Hello, World!")`。 2. **coding**: 编码,指将源代码转换成计算机可以理解的语言的过程...

    C PROGRAMMING TUTORIAL

    - **Influences:** Influenced by earlier languages like BCPL and B, and later influenced languages like C++, Java, and Python. #### Why use C? C is chosen for its simplicity, efficiency, and ...

Global site tag (gtag.js) - Google Analytics