python-文件操作-读、写、二进制文件操作

Python的open函数用于打开文件,mode参数定义了文件的操作模式,如r读取,w写入(覆盖),a追加,b二进制等。使用with语句能确保文件被正确关闭。读文件有read()和readline()等方法,写文件时可使用write(),对于大文件推荐分块读写。二进制模式b适用于处理视频或图像等非文本文件。
摘要由CSDN通过智能技术生成

看python源码定义:

def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open

mode参数:

Character Meaning
    --------- ---------------------------------------------------------------
    'r'       open for reading (default)
    'w'       open for writing, truncating the file first
    'x'       create a new file and open it for writing
    'a'       open for writing, appending to the end of the file if it exists
    'b'       binary mode
    't'       text mode (default)
    '+'       open a disk file for updating (reading and writing)
    'U'       universal newline mode (deprecated)

常用模式:

1、想要写数据到文件,用w或a

#清空原有内容写入
with open(file,mode='w') as f: 
	f.write()
	
#在原有文件后追加写入	
with open(file,mode='a') as f: 
   f.write()

写入文件不会直接写入磁盘,需要关闭文件后,再写入,所以用with open() as f这种更加合理,防止忘记关闭文件

2、想要读取文件内容,用r模式

根据读的文件大小,选择合适的读方法
1 #文件较小:一次读文件全部 f.read()
with open(file,mode='r') as f: 
   f.read()
   
2 #文件较大:可以选择一行一行的读或者指定字节大小的读
with open(file,mode='r') as f: 
   f.read(1024)   # 1024单位为字节

#readlines需要配合循环使用  
with open('../datas/pointCounts.yml','r',encoding="utf-8") as f;
	for lines in f.readlines():
		print(lines.strip())

3、想要操作视频、二进制文件,用b

常用于读取读取一个二进制文件后,在写入另一个文件,类似复制粘贴

 with open('../datas/testbinary.yml', 'wb') as f:
            f.write(fileobj)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值