文件IO主要学习就是open,close
第一个参数 要读写文件路径 第二个参数 以何种方式进行读写
w = write写 r = read读 t = text文本
b = binary字节数据(二进制) a = append追加
import os
一、
1,"w(t)"表示写一个文本文件,并且会将原文件的内容清空
write_file = open("1.txt", "wt")
write_file.write("123123123")
write_file.close()
2,“r(t)”表示读取文本文件
read_file = open("1.txt", "r")
s = read_file.read()
print(s)
当读/写二进制数据的时候使用 r/wb
file:/C:/Users/Shinelon/Desktop/python%20课程/1.txtread_file = open("头像1.png", "rb")
s = read_file.read()
print(s)
3,encoding参数表示文件的编码类型,只有当以文本形式读写文件时encoding才起作用
read_file = open("1.txt","rt",encoding="utf-8")
s = read_file.read()
print(s)
4,a模式会在原文件的内容之后继续添加新内容
append_file = open("tttt.txt", "at")
append_file.write("\n哈哈\n")
append_file.write("呵呵\n")
append_file.close()
5,边读边写
append_file = open("tttt.txt", "rt+")
s = append_file.read()
append_file.write("\n哈哈\n")
append_file.write("呵呵\n")
append_file.close()
6,复制文件
read_file = open("头像1.png","rb")
b = read_file.read()
write_file = open("头像1的副本.png","wb")
write_file.write(b)
read_file.close()
write_file.close()
7,循环读写
read_file = open("13-sys_os模块.mp4","rb")
write_file = open("1.mp4","wb")
while True:
data = read_file.read(1024 * 1024)
if not data:
break
write_file.write(data)
read_file.close()
write_file.close()
8,创建一个copy(src,dst)
src就是源文件的绝对路径 dst就是副本保存的绝对路径
def copy(src,dst):
read_file = open(src,"rb") 创建读取文件的IO
write_file = open(dst,"wb") 创建写入文件的IO
while True:
data = read_file.read(1024 * 1024)
if not data:
break
write_file.write(data)
read_file.close()
write_file.close()
copy('/Users/musicbear/项目:飞机大战.md','1.md')
9,创建一个文件叫做1.txt 写入0-100以内的所有自然数,每写一个数字换一行
f = open("1.txt","wt")
for i in range(0,101):
f.write(f"{i}\n")
f.close()
10,with 关键字在其代码片段执行完毕后会自动释放文件/网络的占用
with open("1.txt","wt") as f:
for i in range(0,101):
f.write(f"{i}\n")
11,读取刚刚写好的文件(1.txt),读取70字节的内容并将其打印到屏幕上
with open("1.txt","rt") as f:
content = f.read(70)
print(content)
12,读取1.txt的所有内容,然后读取到的内容写到2.txt当中
with open("1.txt","rt") as rf:
s = rf.read()
with open("2.txt","wt") as wf:
wf.write(s)
13,读取1.txt中的内容,一次读取10个字节,每读一次,将读到内容写到2.txt中,直到读完整个文件
with open("1.txt","rt") as rf:
with open("2.txt","wt") as wf:
while True:
text = rf.read(10)
if not text:
break
wf.write(text)
def copy(src, dst):
with open(src, "rb") as rf:
with open(dst, "wb") as wf:
while True:
data = rf.read(1024 * 1024)
if not data:
break
wf.write(data)
14,复制指定的目录(imagetest)
①创建指定目录的副本(imagetest_副本)②将目录中的文件都复制一份
③将目录中的子目录进行递归
def copy_dir(src, dst):
os.mkdir(dst) 创建副本文件夹
files = os.listdir(src) 读取src下的所有文件
for f in files:
abs_f = src + os.sep + f
if os.path.isfile(abs_f): 如果是文件,直接复制
copy(abs_f, dst + os.sep + f)
elif os.path.isdir(abs_f):
copy_dir(abs_f, dst + os.sep + f)
copy_dir("/Users/musicbear/imgtest", "/Users/musicbear/imgtest_副本")