查看“Python文本处理”的源代码
←
Python文本处理
跳转至:
导航
,
搜索
因为以下原因,您没有权限编辑本页:
您所请求的操作仅限于该用户组的用户使用:
用户
您可以查看与复制此页面的源代码。
==Python编码解码== <nowiki># -*- coding: utf-8 -*- # 本文件应该保存为utf-8编码,否则会报错 str = "我是中国人" print(f'Unicode字符串为"{str}"') byte0 = str.encode("utf-8") print(f'Unicode字符串"{str}"以utf-8编码得到字节串[{byte0}]') str0 = byte0.decode("utf-8") print(f'将utf-8字节串[{byte0}]解码得到Unicode字符串"{str0}"') byte1 = str.encode("gbk") print(f'Unicode字符串"{str}"以gbk编码得到字节串[{byte1}]') str1 = byte1.decode("gbk") print(f'将gbk字节串[{byte1}]解码得到Unicode字符串"{str1}"') print(f'以文本方式将Unicode字符串"{str}"写入a.txt') with open("a.txt", "w", encoding="gbk") as f: f.write(str) print("以文本方式读取 a.txt 的内容") with open("a.txt", "r", encoding="gbk") as f: print(f.read())</nowiki> ==Python文件读写== <nowiki># -*- coding: utf-8 -*- f = open("wb.txt", "w", encoding="utf-8") f.write("测试w方式写入,如果文件存在,则清空内容后写入,如果文件不存在则创建\n") f.close() f = open("wb.txt", "a", encoding="utf-8") f.write("测试a方式写入,如果文件存在,在文件内容后最后追加写入,如果文件不存在则创建") f.close() f = open("wb.txt", "r", encoding="utf-8") # 以文本方式读,f.read()返回字符串对象 data = f.read() print(type(data)) print(data) f.close() f = open("wb.txt", "rb") # 以文本方式读,f.read()返回字节对象 data = f.read() print(type(data)) print(data) print('将读取的字符对象解码:') print(data.decode('utf-8')) f.close() </nowiki>
返回至
Python文本处理
。
导航菜单
个人工具
登录
命名空间
页面
讨论
变种
视图
阅读
查看源代码
查看历史
更多
搜索
导航
首页
最近更改
随机页面
帮助
工具
链入页面
相关更改
特殊页面
页面信息