python自学第6天,文件修改,字符编码

时间:2023-03-08 17:16:10
python自学第6天,文件修改,字符编码

文件的修改:

一般是把旧文件的内容改了,在写入到新的文件中去。

file_old=open("test","r",encoding="utf-8")
file_new=open("test.bak","w",encoding="utf-8") for line in file_old:
if "快乐等我享受" in line:
line=line.replace("快乐等我享受","快乐等HunterYi享受")
print(line)
file_new.write(line)
file_old.close()
file_new.close()

  

with语句的用法。

#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author:Hunter Yi with open("test","r",encoding="utf-8") as f ,\
open("test.bak","r",encoding="utf-8") as f2: #用with语句 可以同时打开多个文件,用完后自动关闭。 for line in f:
print(line) for line2 in f2:
print(line2)  

查看当前编码

import sys
print(sys.getdefaultencoding()) 编码转换
s_utf8="你好"
print(s_utf8.encode("utf-8"))
utf8_gbk=s_utf8.encode("gbk")
print(utf8_gbk)
gbk_gb2312=utf8_gbk.decode("gbk").encode("utf-8")
print(gbk_gb2312.decode("utf-8"))

python自学第6天,文件修改,字符编码