"""
文件操作
"""
# 创建一个文件
# 写入hello.
"""
my_file = None
try:
# open("路径","操作模式",encoding="utf-8")
my_file = open("my_file01.txt","w",encoding="utf-8")
# my_file.write("hello\n")
# my_file.write("你好")
my_file.write("好吗你?")
finally:
# 如果文件不是空 则关闭
if my_file!=None:
my_file.close()
"""
# with open("my_file01.txt","w",encoding="utf-8") as my_file:
# my_file.write("好吗你?")
# # my_file.close() 当程序执行到with代码块以外,一定会执行close()
# 创建文件夹:
import os
# 不是文件夹或者不存在该文件夹,返回false
# print(os.path.isdir("file_demo"))
# 如果不是文件夹
if not os.path.isdir("file_demo"):
# 创建文件夹(支持多个)os.makedirs("file_demo/a/b/c")
os.makedirs("file_demo")
# 操作文件:
with open("file_demo/my_file01.txt","w",encoding="utf-8") as my_file:
my_file.write("好吗你?")
# my_file.close() 当程序执行到with代码块以外,一定会执行close()
"""
文件操作模式
"""
# 1. w 只写 : 如果文件不存在,则创建。每次都从头写入(清空之前的内容)。
with open("file_demo/my_file02.txt","w",encoding="utf-8") as my_file:
my_file.write("写入文字\n")
str_list=["a\n","b\n","c\n"]
my_file.writelines(str_list)
# 2. a 追加:如果文件不存在,则创建。每次都从末尾写入
with open("file_demo/my_file02.txt","a",encoding="utf-8") as my_file:
my_file.write("写入文字\n")
str_list=["a\n","b\n","c\n"]
my_file.writelines(str_list)
# 3. 只读
with open("file_demo/my_file02.txt","r",encoding="utf-8") as my_file:
# 读取所有内容
print(my_file.read())
# 读取指定数量的字符
print(my_file.read(6))
# 读取一行
print(my_file.readline())
# 迭代读取
for line in my_file:
print(line)
文件二进制操作
"""
文件二进制操作
"""
# 字节串:存储字节
b01 = b"a" # 97
print(type(b01)) # bytes
# 对二进制文件进行读写操作
with open("MVC.jpg","r+b") as my_file:
#1. 获取文件操作位置
print(my_file.tell())# 返回需要操作的位置 0
#2. 读取文件字节
temp_bytes = my_file.read()
#3. 设置文件操作位置
my_file.seek(0)
print(my_file.tell()) # 0
# 反转
temp_bytes = temp_bytes[::-1]
#4. 写入字节
my_file.write(temp_bytes)