Python中使用不同编码读写txt文件详解
import os
import codecs
filenames=os.listdir(os.getcwd())
out=file("name.txt","w")
for filename in filenames:
out.write(filename.decode("gb2312").encode("utf-8"))
out.close()
将执行文件的当前目录及文件名写入到name.txt文件中,以utf-8格式保存
如果采用ANSI编码保存,用如下代码写入即可:
out.write(filename)
打开文件并写入
引用codecs模块,对该模块目前不了解。在此记录下方法,有空掌握该模块功能及用法。
import codecs
file=codecs.open("lol.txt","w","utf-8")
file.write(u"我")
file.close()
读取ANSI编码的文本文件和utf-8编码的文件
读取ANSI编码文件
建立一个文件test.txt,文件格式用ANSI,内容为:
abc中文
用python来读取
# coding=gbk
print open("Test.txt").read()
结果:abc中文
读取utf-8编码文件(无BOM)
把文件格式改成UTF-8:
结果:abc涓 枃
显然,这里需要解码:
# -*- coding: utf-8 -*-
import codecs
print open("Test.txt").read().decode("utf-8")
结果:abc中文
读取utf-8编码文件(有BOM)
某些软件在保存一个以UTF-8编码的文件时,默认会在文件开始的地方插入三个不可见的字符(0xEF 0xBB 0xBF,即BOM)。在有些软件可以控制是否插入BOM。如果在有BOM的情况下,在读取时需要自己去掉这些字符,python中的codecs module定义了这个常量:
# -*- coding: utf-8 -*-
import codecs
data = open("Test.txt").read()
if data[:3] == codecs.BOM_UTF8:
data = data[3:]
print data.decode("utf-8")
结果:abc中文
在看下面的例子:
# -*- coding: utf-8 -*-
data = open("name_utf8.txt").read()
u=data.decode("utf-8")
print u[1:]
打开utf-8格式的文件并读取utf-8字符串后,解码变成unicode对象。但是会把附加的三个字符同样进行转换,变成一个unicode字符。该字符不能被打印。所以为了正常显示,采用u[1:]的方式,过滤到第一个字符。
注意:在处理unicode中文字符串的时候,必须首先对它调用encode函数,转换成其它编码输出。
设置python默认编码
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
print sys.getdefaultencoding()
今天碰到了 python 编码问题, 报错信息如下
Traceback (most recent call last):
File "ntpath.pyc", line 108, in join
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa1 in position 36: ordinal not in range(128)
显然是当前的编码为ascii, 无法解析0xa1(十进制为161, 超过上限128). 进入python console后, 发现默认编码确实是 ascii, 验证过程为:
在python2.6中无法调用sys.setdefaultencoding()函数来修改默认编码,因为python在启动的时候会调用site.py文件,在这个文件中设置完默认编码后会删除sys的setdefaultencoding方法。不能再被调用了. 在确定sys已经导入的情况下, 可以reload sys这个模块之后, 再 sys.setdefaultencoding('utf8')
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
print sys.getdefaultencoding()
确实有效, 根据 limodou 讲解, site.py 是 python 解释器启动后, 默认加载的一个脚本. 如果使用 python -S 启动的话, 将不会自动加载 site.py.
上面写的挺啰嗦的.
==================================
如何永久地将默认编码设置为utf-8呢? 有2种方法:
==================================
第一个方法: 编辑site.py, 修改setencoding()函数, 强制设置为 utf-8
第二个方法: 增加一个名为 sitecustomize.py, 推荐存放的路径为 site-packages 目录下
sitecustomize.py 是在 site.py 被import 执行的, 因为 sys.setdefaultencoding() 是在 site.py 的最后删除的, 所以, 可以在 sitecustomize.py 使用 sys.setdefaultencoding().
import sys
sys.setdefaultencoding('utf-8')
既然 sitecustomize.py 能被自动加载, 所以除了设置编码外, 也可以设置一些其他的东西
字符串的编码
s1='中文'
像上面那样直接输入的字符串是按照代码文件的编码来处理的,如果是unicode编码,有以下三种方式:
1 s1 = u'中文'
2 s2 = unicode('中文','gbk')
3 s3 = s1.decode('gbk')
unicode是一个内置函数,第二个参数指示源字符串的编码格式。
decode是任何字符串具有的方法,将字符串转换成unicode格式,参数指示源字符串的编码格式。
encode也是任何字符串具有的方法,将字符串转换成参数指定的格式。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
