读写文件

读取文件

r 模式表示读取文件;

Python 引用 with 语句自动调用 close() 用法 (人性化无疑

with open('/path/to/file/', 'r') as f: # r模式读取文件(文件名:f)
    f.read() # read()读取文件内容

read() 会一次读取文件全部内容。如果文件有20G,内存直接爆炸
保险起见建议调用 read(size)

with open('/path/to/file/", 'r') as f:
    f.read(5) # read(5)读取文件内容前5个字节

另外,可以调用 readline() 方法将文件每次读取一行内容

with open('/path/to/file/', 'r') as f:
    f.readline() # readline()读取文件前一行

也可调用 readlines() 一次读取文件所有内容并返回 list

with open('/path/to/file/', 'r') as f:
    for line in f.readlines: # 调用readlines()并逐行输出
        print(line.strip()) # strip()删掉文末的'\n'

编写文件

w 模式表示编写文件文本wb 模式表示编写二进制文本

若调用单纯的 open('/path/to/file/', 'w') 编写文件需要 close() 语句关闭文件以保证编入的数据完整存入文件,否则会丢失后面一部分的数据(因为系统不会立刻将数据编入文件,而是缓缓编入;只有调用 close() 才保证系统将后续数据编入文件)

而此时调用 with 语句更加保险:

with open('/path/to/file/', 'w') as f:
    f.write('Hello, Python!') # write()编写文件

对于多个文件的读写

  1. 嵌套
with open('/path/to/file/', 'r+') as f1:
    with open('/path/to/file/', 'r+';) as f2:
        with open('/path/to/file/';, 'r+') as f3:
        ······
        ······
        ······
  1. 暴力
with open('/path/to/file/', 'r+') as f1:
······
with open('/path/to/file/', 'r+') as f2:
······
with open('/path/to/file/', 'r+') as f3:
······

文件读写方式

File 对象属性

Reference

python 使用 with open() as 读写文件

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值