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也是任何字符串具有的方法,将字符串转换成参数指定的格式。

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies

forloopsareadvantageousforknowniterations and sequests,供应模拟性和可读性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

Dreamweaver CS6
视觉化网页开发工具

Atom编辑器mac版下载
最流行的的开源编辑器

Dreamweaver Mac版
视觉化网页开发工具