专题:Python文件操作

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', '低头思故乡。']

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值