一、open函数
1、mode
r w rb wb
r : read | 纯文本文件 |
w : write | |
rb : read binary | 纯文本、图片、音乐、电影 |
wb : write binary |
2、open函数
open( file,mode,buffering,encodeing )
(1)读文件
open(path/filename,'rt') ---返回值:stream(管道) stream.read() ---读取管道内存
如果传递的path/filename有误,则会报错:FileNotFoundError
如果是图片则不能使用默认的读取方式 mode='rb'
- read() 读取所有内容
stream = open(r'C:\Users\刘楠\PycharmProjects\pythonstudy\aa.txt')
container = stream.read()
print(container)
- readline() 每次读取一行内容
while True:
line = stream.readline()
print(line)
if not line:
break
- readlines() 读取所有的行保存到列表
lines = stream.readlines() # 保存到列表
print(lines)
for i in lines:
print(i)
- readable() 判断是否可读
result = stream.readable() # 判断是否可以读取 True False
print(result)
stream = open('C:\Users\刘楠\PycharmProjects\pythonstudy\a1.jpg','rb')
container = stream.read()
print(container)
(2)写文件
stream = open(r'C:\pythonstudy\aa.txt','w')
mode = 'w' 表示写操作
- write(内容) 每次都会将原来的内容清空,然后写当前内容
- writelines(Iterable) 没有换行效果 s.writelines(['赌神\n','小刀\n','周