11 文件
一、文件的基本操作
1、打开关闭文件
# 传入表示文件路径的字符串,会返回一个文件对象。
f = open(file_path,mode='r') # file_path 文件路径
f.close() # 关闭文件
with open(file_path,mode='r') as f : # 使用with open 可以不用close函数来关闭文件
pass
2、写入文件
write、writelines
f1 = open("test.txt", mode="w", encoding="utf-8")
f1.write("""
白日依山尽,
黄河入海流。
""")
# 遍历对象依次写入
f1.writelines(['1\n', '2\n', '3\n'])
f1.close()
# 白日依山尽,
# 黄河入海流。
# 1
# 2
# 3
3、读取文件
read、readline、readlines
f2 = open("test.txt",mode = "r",encoding="utf-8")
# reader = f2.read()
# print(reader)
# print(f2.readline()) # 第一行
print(f2.readlines()) # 返回一个包换所有行的列表
f2.close()
4、tell()
返回光标的位置
with open("test.txt",mode = "r",encoding="utf-8") as f3:
print(f3.tell()) # 0
reader = f3.read()
print(f3.tell()) # 42
5、seek()
设置光标的位置
with open("test.txt", mode="r", encoding="utf-8") as f3:
print(f3.tell()) # 0
reader = f3.read()
print(f3.tell()) # 42
f3.seek(20)
print(f3.tell()) # 20
6、二进制读写
f1 = open("image/1.jpg",mode = "rb")
f2 = open("image/123.jpg",mode = "wb")
reader = f1.read()
print(list(reader))
f2.write(reader)
f1.close()
f2.close()
二、上下文管理
上下文管理:写代码前后做的事情
# with调用了__enter__,__exit__两个魔术方法
from datetime import datetime
class Runtime:
def __enter__(self): # 进入时自动调用
self.starttime = datetime.now()
# print(self.starttime)
return self.starttime
def __exit__(self,exc_type,exc_val,exc_tb): # 退出时自动调用
self.endtime = datetime.now()
print(self.endtime)
print("运行时间:",self.endtime - self.starttime)
run = Runtime()
with run as a:
for i in range(1000):
print(a)
# 运行时间: 0:00:00.008000
三、IO流
import io
# 字符流
sio = io.StringIO()
sio.write("hello") # 写入
reader = sio.getvalue()
print(reader) # hello
sio.close() # close后内存释放
# 字节流
bio = io.BytesIO()
bio.write(b"hello")
reader = bio.getvalue()
print(reader) # b'hello'
bio.close() # close后内存释放
四、常用工具
1、os模块
(python和操作系统交互的模块)
import os
# 输入 ls pwd 指令
os.system("ls")
os.system("pwd")
# 获取当前路径
print(os.getcwd())
# 获取当前路径
project_dir=os.path.abspath(os.path.dirname(__file__))
print(project_dir) # G:\复习1\01 python基础\11 文件
newdir = os.path.join(project_dir,'images')
print(newdir) # G:\复习1\01 python基础\11 文件\images
# 将多个路径组合后返回(路径拼接)
t1 = os.path.join("pyvip","yun",hello)
print(t1)
os.mkdir("class") # 创建文件夹,如果已存在,报错
os.rename("class","test") # 修改文件夹名字
print(dir(os))
2、 shutil 模块
高级文件操作
import shutil
# 将文件移动到目标文件夹
shutil.move("","") #目标文件夹放后面
# 将前一个文件夹里的文件,复制到后面的文件路径下
shutil.copytree("","")
# 删除目标文件夹
shutil.rmtree("")