1. 文件操作及相关函数

day08-Python运维开发基础(文件操作与相关函数、函数基础)

  

# ### 文件操作
"""
fp = open("文件名称",mode=模式,encoding=编码集)
fp 文件io对象 (文件句柄)
i : input  输入
o : output 输出
"""

# (1) 文件的写入操作
# 打开文件
fp = open("ceshi1.txt",mode="w",encoding="utf-8")# 打开冰箱
# 写入内容
fp.write("把大象塞进去") # 把大象放进去
# 关闭文件
fp.close()# 关上冰箱

# (2) 文件的读取操作
# 打开文件
fp = open("ceshi1.txt",mode="r",encoding="utf-8")
# 读取内容
res = fp.read()
# 关闭文件
fp.close()
print(res)


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

# encode
strvar = "我爱你"
res = strvar.encode("utf-8")
print(res)
# decode
strnew = res.decode("utf-8")
print(strnew)

# 三个字节代表一个中文
res = b"\xe7\x88\xb1".decode()
print(res)

# (4) 写入字节流 (不要指定字符编码encoding)
fp = open("ceshi2.txt",mode="wb")
str_bytes = "我爱你,亲爱你菇凉".encode("utf-8")
fp.write(str_bytes)
fp.close()

# (5) 读取字节流 (不要指定字符编码encoding)
fp = open("ceshi2.txt",mode="rb")
res = fp.read()
fp.close()
print(res)

content = res.decode("utf-8")
print(content)

# 复制图片操作 (图片,音乐,视频 ... 二进制字节流模式)
# 读取旧图片
fp = open("集合.png",mode="rb")
str_bytes = fp.read()
fp.close()

# 创建新图片
fp = open("集合2.png",mode="wb")
fp.write(str_bytes)
fp.close()
文件操作 示例代码

相关文章: