文章目录
文件
1.基础的读写
f = open("demo.txt",'w',encoding='utf-8') #相对地址
f.write("张学成最帅")
f.close()
f = open("demo.txt",'r',encoding='utf-8') #相对地址
print(f.read())
f.close()
2.write和writelines的区别
f = open("demo.txt",'w',encoding='utf-8') #相对地址
f.write("张学成最帅")
f.writelines(['wfajlkwf\n','2'])
f = open("demo.txt",'r',encoding='utf-8') #相对地址
print(f.read())
f.close()
这两个都能写入字符串,但是readlines可以写入字符组,但是不能是数字只能是字符串(但是说实话感觉没啥区别)
3.with方法
with open("zxc.txt", "w", encoding="utf-8") as f:
f.writelines(["zxc\n", "6\n", "666\n"])
with open("zxc.txt", "r", encoding="utf-8") as f:
print(f.read())
3.1光标和位移
with open("zxc.txt", "w", encoding="utf-8") as f:
f.writelines(["zxc\n", "6\n", "666\n"])
with open("zxc.txt", "r", encoding="utf-8") as f:
print(f.read())
print(f.tell())
f.seek(0)
print(f.tell())
注意:tell()是说明当前光标所在位置,如果读的话在开始(0),写在最后,seek(x)是移动到位置为x的地方,x从零开始,以字节为单位,但是在utf-8中汉字为3个字节,字母为一个字节,所以如果乱移动就会出现乱码
3.2非二进制文件的写入(一般用于把图片拷贝到本地)
3.3追加“a”(文件不存在就创建文件)
with open("zxc.txt","a",encoding="utf-8")as f:
f.write("lalalala")
4.a+,w+,r+的用法
with open("zxc.txt", "w+", encoding="utf-8")as f:
f.write("naffnawklawfk")
print(f.tell())
f.seek(0)
print(f.read())
切记写的时候,光标会移动方向,所以如果直接读就会none,这三种方式都能读写,所以很方便,另外两个就不演示了