python-文件的操作

#python万物皆对象,那么我把打开文件open()作为一个对象,创建对象f

f = open('C:\\PHP+python\\python\\1.txt',mode='r',encoding='utf-8') #mode='r'设置文件为只读,打开编码为utf-8(文件中有中文)
file = f.read()#调研对象f的read方法

print (file)
#文件用完及时关闭
f.close()



f = open('C:\\PHP+python\\python\\1.txt',mode='rb',) #mode='r'设置文件为只读,打开编码为默认(文件中没有中文)
file = f.read()#调研对象f的read方法

print (file)
#文件用完及时关闭
f.close()

只读:r
f = open('C:\\PHP+python\\python\\1.txt',mode='rb',)
file = f.read()


只写:w
    
#对于写,没有此文件就会创建
    #有文件,讲文件清空再写
f = open('C:\\PHP+python\\python\\1.txt',mode='w',encoding='utf-8')
file = f.write('写的内容')

f.close()
  wb:

f = open('C:\\PHP+python\\python\\1.txt',mode='wb',)#(b,bytes类型)
file = f.write('写的内容'.encode('utf-8'))#将bytes类型转换成utf-8
f.close()

追加:a
f = open('C:\\PHP+python\\python\\1.txt',mode='a',encoding='utf-8')
file = f.write('写的内容')

f.close()



 

转载于:https://www.cnblogs.com/Py-Raid/p/9738664.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值