python open写入_python文件读写 with open()

本文介绍了Python中`with open()`函数的使用,特别是文件的读写模式。文章详细解析了模式参数,如'r'(读取)、'w'(写入,覆盖)、'x'(新建并写入)、'a'(追加)等,并强调在使用pickle.dump()序列化对象时,应选择二进制模式。
摘要由CSDN通过智能技术生成

一、文件写入和读取

def write(self, data): # 写入

with open(self.filename, 'ab') as f:

pickle.dump(data, f)

def readiter(self): # 读取

with open(self.filename, 'rb') as f:

while True:

try:

data = pickle.load(f)

yield data

except:

break

二、python源码解释

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

"""

Open file and return a stream. Raise OSError upon failure.

file is either a text or byte string giving the name (and the path

if the file isn't in the current working directory) of the file to

be opened or an integer file descriptor of the file to be

wrapped. (If a file descriptor is given, it is closed when the

returned I/O object is closed, unless closefd is set to False.)

mode is an optional string that specifies the mode in which the file

is opened. It defaults to 'r' which means open for reading in text

mode. Other common values are 'w' for writing (truncating the file if

it already exists), 'x' for creating and writing to a new file, and

'a' for appending (which on some Unix systems, means that all writes

append to the end of the file regardless of the current seek position).

In text mode, if encoding is not specified the encoding used is platform

dependent: locale.getpreferredencoding(False) is called to get the

current locale encoding. (For reading and writing raw bytes use binary

mode and leave encoding unspecified.) The available modes are:

========= ======================================================

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值