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