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



 
posted @ 2018-10-04 08:01  py_tobe  阅读(114)  评论(0)    收藏  举报