文件操作

# ### 文件操作
'''
fp = open("文件名",mode="采用的模式",encodng="使用什么编码集")
fp 这个变量会接受到 open的返回值 是一个文件io对象 (又称文件句柄)
i => input  输入
o => output 输出
有了对象之后,就可以使用对象.属性 或者 对象.方法进行操作.

fp.write("字符串")
fp.close()
fp.read() 读取内容
'''

# (1) 文件的写入和读取
# 写入文件
'''
# 打开文件
fp = open("0506.txt",mode="w",encoding="utf-8")# 把冰箱门打开
# 写入文件
fp.write("把大象放到冰箱里面")# 把大象塞进去
# 关闭文件
fp.close()# 把冰箱门关上
'''
# 读取文件
'''
# 打开文件
fp = open("0506.txt",mode="r",encoding="utf-8")# 把冰箱门打开
# 读取文件
res = fp.read()# 把大象从冰箱里面拿出来
# 关闭文件
fp.close()# 把冰箱门关上
print(res)
'''

# 将字符串和字节流(Bytes流)类型进行转换 (参数写成转化的字符编码格式)
    #encode() 编码  将字符串转化为字节流(Bytes流)
    #decode() 解码  将Bytes流转化为字符串

strvar = "今天"
byt = strvar.encode("utf-8")
print(byt)
res2 = byt.decode("utf-8")
print(res2)

# (2) wb 和 rb 模式 二进制字节流模式 (注意点:使用字节流模式的时候,不要指定encoding)

# 文件的写入
fp = open("0506_2.txt",mode="wb")
strvar = "好晴朗"
res = strvar.encode("utf-8")
fp.write(res)
fp.close()

# 文件的读取
fp = open("0506_2.txt",mode="rb")
res = fp.read()
fp.close()
print(res)
res2 = res.decode("utf-8")
print(res2)

# (3) 复制图片 (图片或者视频之类的二进制字节流的内容 , 都可以使用b模式 比如wb , rb ..)
# 打开文件
fp = open("ceshi.png",mode="rb")
# 读取文件
res = fp.read()
# 关闭文件
fp.close()

# 打开文件
fp = open("ceshi2.png",mode="wb")
# 写入文件
fp.write(res)
# 关闭文件
fp.close()

  

原文地址:https://www.cnblogs.com/huangjiangyong/p/10823136.html