1、with open('文件名', '操作模式') as 别名:
如果只用open()来打开文件的话,在操作文件完成后要用close()来手动关闭文件,而with open不需要手动关闭文件。
2、open()打开csv文件时,newline参数的作用:
经过实操,暂时没有发现有newline参数和没有newline二者有什么区别
3、w和wb的区别,r和rb的区别
注:二进制的读写在图片和视频的读写中经常用到。
3.1 用w写文件,用r读文件
with open('test.txt', 'w') as file:
file.write('hello\nworld')
with open('test.txt', 'r') as file:
print(file.read())
# 输出:
hello
world
3.2 用w写文件,用rb读文件
with open('test.txt', 'w') as file:
file.write('hello\nworld')
with open('test.txt', 'rb') as file:
print(file.read())
# 输出:
b'hello\nworld'
3.3 用wb写文件,用r读文件
with open('test.txt', 'wb') as file:
file.write(b'hello\nworld')
with open('test.txt', 'r') as file:
print(file.read())
# 输出:
hello
world
3.4 用wb写文件,用rb读文件
with open('test.txt', 'wb') as file:
file.write(b'hello\nworld')
with open('test.txt', 'rb') as file:
print(file.read())
# 输出:
b'hello\nworld'
4、read(), readline()和readlines()三者的区别
先准备一个txt文件:
4.1 read()方法从文件当前位置起读取至文件结束为止,它的返回值为字符串对象:
with open('test.txt', 'r') as file:
data = file.read()
print(type(data))
print(data)
# 输出:
<class 'str'>
床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。
4.2 readline()方法每次读出一行内容,所以,读取时占用内存小,比较适合大文件,该方法返回一个字符串对象:
with open('test.txt', 'r') as file:
data = file.readline()
print(type(data))
print(data)
# 输出:
<class 'str'>
床前明月光,
4.3 readlines()读取整个文件所有行,保存在一个列表(list)变量中,每行作为一个元素,但读取大文件会比较占内存:
with open('test.txt', 'r') as file:
data = file.readlines()
print(type(data))
print(data)
# 输出:
<class 'list'>
['床前明月光,\n', '疑是地上霜。\n', '举头望明月,\n', '低头思故乡。']