文件

文件

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()

[外链图片转存失败(img-JHEXK03n-1564988194443)(../../AppData/Roaming/Typora/typora-user-images/1562396316045.png)]

这两个都能写入字符串,但是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())

[外链图片转存失败(img-wngTjmES-1564988194443)(../../AppData/Roaming/Typora/typora-user-images/1562412057383.png)]

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())

[外链图片转存失败(img-9VPSkrDZ-1564988194443)(../../AppData/Roaming/Typora/typora-user-images/1562412480107.png)]

注意:tell()是说明当前光标所在位置,如果读的话在开始(0),写在最后,seek(x)是移动到位置为x的地方,x从零开始,以字节为单位,但是在utf-8中汉字为3个字节,字母为一个字节,所以如果乱移动就会出现乱码

3.2非二进制文件的写入(一般用于把图片拷贝到本地)

[外链图片转存失败(img-wLVBR9G0-1564988194444)(../../AppData/Roaming/Typora/typora-user-images/1562467460801.png)]

3.3追加“a”(文件不存在就创建文件)
with open("zxc.txt","a",encoding="utf-8")as f:
    f.write("lalalala")

[外链图片转存失败(img-S50mgvNN-1564988194444)(../../AppData/Roaming/Typora/typora-user-images/1562467864828.png)]

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())

[外链图片转存失败(img-poQ5M5V2-1564988194444)(../../AppData/Roaming/Typora/typora-user-images/1562468652177.png)]

切记写的时候,光标会移动方向,所以如果直接读就会none,这三种方式都能读写,所以很方便,另外两个就不演示了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值