6.5 文件
下面是一个文件的常用函数 ,需要导入import io
返回类型 | 函数名及参数 | 说明 | 示例 |
---|---|---|---|
file object | open(file,mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) | 打开文件,并返回文件对象。第一个参数是文件名,第二个参数是打开模式,默认为只读模式。 | f = open("test.txt", "r") |
None | file.close() | 关闭文件。在处理完文件后一定要关闭文件,否则会占用系统资源。 | f.close() |
string | file.read([size]) | 读取指定字节数的文件内容。如果省略参数,则读取整个文件。 | f = open("test.txt", "r") f.read() f.close() |
string | file.readline() | 读取文件中一行的内容。 | f = open("test.txt", "r") f.readline() f.close() |
list | file.readlines() | 读取整个文件的内容,并返回每一行的列表,每行是一个元素。 | f = open("test.txt", "r") f.readlines() f.close() |
None | file.write(str) | 将指定字符串写入文件。需要注意的是,如果调用了write方法,一定要在最后调用close方法,否则文件不会被保存。 | f = open("test.txt", "w") f.write("hello world") f.close() |
integer | file.tell() | 返回当前在文件中的位置。 | f = open("test.txt", "r") f.tell() f.close() |
None | file.seek(offset[, whence]) | 将文件指针移动到指定位置。 | f = open("test.txt", "r") f.seek(10) f.close() |