文件读写在python编程中占有重要的作用,接下来几天都会学习文件的读写
常用模块:
‘r’:读
‘w’:写
‘a’:追加
首先是创建文件以及写入文件的代码:
with open ("1.txt",'w',encoding='UTF-8') as f:
f.write('123')
f.write('I love China')
f.write('你的名字')
此时,对应目录下会出现 1.txt ,并在txt文档中写入相应的文字(该种输入方式不会出现换行);
当把模式改为’a’时:
with open ("1.txt",'a',encoding='UTF-8') as f:
f.write('123\n')
f.write('I love China\n')
f.write('你的名字\n')
则在文件中追加新输入的文字;
其次,是读文本文件的代码:
常用读取方式:
‘read’:指定一次读多少个字符
‘readline’:默认换行
‘readlines’:读取的是个列表,每行为一个列表元素
with open ("1.txt",encoding='UTF-8') as f:
while 1:
txt=f.read(2)
if txt:
print(txt)
else:
break
with open ("1.txt",encoding='UTF-8') as f:
while 1:
txt=f.readline()
if txt:
print(txt)
else:
break
with open ("1.txt",encoding='UTF-8') as f:
while 1:
txt=f.readlines()
if txt:
print(txt)
else:
break
输出的对应结果如下图:
其次,是读二进制文件的代码:(如图片)
此时,需要把 ‘r’ 模式改为 ‘rb’
代码如下:
with open("1.jpg",'rb')as f:
t=f.read(13)
#图片的二进制代码前三位均为'\xff\xd8\xff'
if t==b'\xff\xd8\xff':
print("jpg文件")
print(t,type(t))
当想要实现图片的复制的时候,一般的操作是先读后写
代码如下:
with open("1.jpg",'rb')as f:
t=f.read()
with open("3.jpg",'wb')as f:
f.write()
嗯嗯~就酱紫