python内置函数open_python open内置函数:模式a,a,w,w和r之间的区别?

打开模式与C标准库函数 fopen() 完全相同 .

The argument mode points to a string beginning with one of the following

sequences (Additional characters may follow these sequences.):

``r'' Open text file for reading. The stream is positioned at the

beginning of the file.

``r+'' Open for reading and writing. The stream is positioned at the

beginning of the file.

``w'' Truncate file to zero length or create text file for writing.

The stream is positioned at the beginning of the file.

``w+'' Open for reading and writing. The file is created if it does not

exist, otherwise it is truncated. The stream is positioned at

the beginning of the file.

``a'' Open for writing. The file is created if it does not exist. The

stream is positioned at the end of the file. Subsequent writes

to the file will always end up at the then current end of file,

irrespective of any intervening fseek(3) or similar.

``a+'' Open for reading and writing. The file is created if it does not

exist. The stream is positioned at the end of the file. Subse-

quent writes to the file will always end up at the then current

end of file, irrespective of any intervening fseek(3) or similar.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 中,内置函数 `open()` 用于打开文件,并返回一个文件对象。`open()` 函数的第一个参数是文件名,第二个参数是打开文件的模式。常见的文件打开模式包括: - `r`:只读模式,打开文件后只能读取文件内容,不能修改文件。如果文件不存在,会抛出异常。 - `w`:只写模式,打开文件后会清空文件内容,如果文件不存在则会创建文件。如果文件已经存在,则会覆盖原有内容。 - `a`:追加模式,打开文件后会将新的内容添加到文件末尾,如果文件不存在则会创建文件。 - `b`:二进制模式,用于打开二进制文件,例如图片、视频等。 - `+`:读写模式,用于打开文件后可以读写文件。 根据这些模式,可以得到以下几种常见的模式组合: - `r+`:读写模式,打开文件后可以读取和修改文件内容。如果文件不存在,会抛出异常。 - `w+`:读写模式,打开文件后会清空文件内容,如果文件不存在则会创建文件。如果文件已经存在,则会覆盖原有内容。 - `a+`:读写模式,打开文件后会将新的内容添加到文件末尾,如果文件不存在则会创建文件,可以读取和修改文件内容。 需要注意的是,在写模式下使用文件对象的 `write()` 方法写入数据时,需要使用 `\n` 来表示换行符。例如: ```python with open('test.txt', 'w') as f: f.write('Hello, world!\n') ``` 而在读取文件时,可以使用 `read()` 方法读取文件的全部内容,也可以使用 `readline()` 方法每次读取一行。例如: ```python with open('test.txt', 'r') as f: content = f.read() print(content) ``` 这里使用 `read()` 方法读取整个文件的内容,然后将其输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值