16. 读写文件——Python官网语法摘录

1. open(filename, mode)

返回 file object。

>>> f = open('workfile', 'w')

第一个参数:文件名字符串。
第二个参数: ‘r’ 文件只读,‘w’ 只写(已存在的同名文件会被删除), ‘a’ 打开文件追加内容,‘r+’ 打开文件读写。默认为 ‘r’。 ‘b’ 以 binary mode 打开文件,用于所有不包含文本的文件。

3. with

使用 with 相比等效的 try-finally 代码块要简短得多:

>>> with open('workfile') as f:
...     read_data = f.read()

>>> # We can check that the file has been automatically closed.
>>> f.closed
True
3. read(size)

读取一些数据并将其作为字符串或字节串对象返回。
size 是一个可选的数值参数。 当 size 被省略或者为负数时,将读取并返回整个文件的内容,如果文件的大小是你的机器内存的两倍就会出现问题。
当取其他值时,将读取并返回至多 size 个字符(在文本模式下)或 size 个字节(在二进制模式下)。
如果已到达文件末尾,f.read() 将返回一个空字符串 (’’)。

>>>
>>> f.read()
'This is the entire file.\n'
>>> f.read()
''
4. readline()

从文件中读取一行
f.readline() 返回一个空的字符串,则表示已经到达了文件末尾。

>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''
>>> for line in f:
...     print(line, end='')
...
This is the first line of the file.
Second line of the file
5. write(string)

把 string 的内容写入到文件中,并返回写入的字符数

>>> f.write('This is a test\n')
15

在写入其他类型的对象之前,需要转化为字符串

>>> value = ('the answer', 42)
>>> s = str(value)  # convert the tuple to string
>>> f.write(s)
18
6. tell()

返回一个整数,给出文件指针在文件中的位置

7. seek(offset, whence)

改变文件文件指针位置
whence 0从文件开头起算,1 使用当前文件位置,2 使用文件末尾作为参考点。 whence 省略则默认值为 0。

>>> f = open('workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)      # Go to the 6th byte in the file
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2)  # Go to the 3rd byte before the end
13
>>> f.read(1)
b'd'

————Blueicex 2020/07/19 18:45 blueice1980@126.com

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值