整理平常经常用到的文件对象方法:
f.readline() 逐行读取数据
方法一:
1 >>> f = open("/tmp/test.txt")2 >>>f.readline()3 "hello girl! "4 >>>f.readline()5 "hello boy! "6 >>>f.readline()7 "hello man!"8 >>>f.readline()9 ""
方法二:
1 >>> for i in open("/tmp/test.txt"):2 ... print i3 ...4 hello girl!
5 hello boy!
6 hello man!
7 f.readlines() 将文件内容以列表的形式存放8
9 >>> f = open("/tmp/test.txt")10 >>>f.readlines()11 ["hello girl! ", "hello boy! ", "hello man!"]12 >>> f.close()
f.next() 逐行读取数据,和f.readline() 相似,唯一不同的是,f.readline() 读取到最后如果没有数据会返回空,而f.next() 没读取到数据则会报错
1 >>> f = open("/tmp/test.txt")2 >>>f.readlines()3 ["hello girl! ", "hello boy! ", "hello man!"]4 >>>f.close()5 >>>
6 >>> f = open("/tmp/test.txt")7 >>>f.next()8 "hello girl! "9 >>>f.next()10 "hello boy! "11 >>>f.next()12 "hello man!"13 >>>f.next()14 Traceback (most recent call last):15 File "", line 1, in
16 StopIteration
f.writelines() 多行写入
1 >>> l = [" hello dear!"," hello son!"," hello baby! "]2 >>> f = open("/tmp/test.txt","a")3 >>>f.writelines(l)4 >>>f.close()5 [root@node1 python]#cat /tmp/test.txt
6 hello girl!
7 hello boy!
8 hello man!
9 hello dear!
10 hello son!
11 hello baby!
f.seek(偏移量,选项)
1 >>> f = open("/tmp/test.txt","r+")2 >>>f.readline()3 "hello girl! "4 >>>f.readline()5 "hello boy! "6 >>>f.readline()7 "hello man! "8 >>>f.readline()9 " "10 >>>f.close()11 >>> f = open("/tmp/test.txt","r+")12 >>>f.read()13 "hello girl! hello boy! hello man! "14 >>>f.readline()15 ""16 >>> f.close()
这个例子可以充分的解释前面使用r+这个模式的时候,为什么需要执行f.read()之后才能正常插入
f.seek(偏移量,选项)
(1)选项=0,表示将文件指针指向从文件头部到“偏移量”字节处
(2)选项=1,表示将文件指针指向从文件的当前位置,向后移动“偏移量”字节
(3)选项=2,表示将文件指针指向从文件的尾部,向前移动“偏移量”字节
偏移量:正数表示向右偏移,负数表示向左偏移
1 >>> f = open("/tmp/test.txt","r+")2 >>> f.seek(0,2)3 >>>f.readline()4 ""5 >>> f.seek(0,0)6 >>>f.readline()7 "hello girl! "8 >>>f.readline()9 "hello boy! "10 >>>f.readline()11 "hello man! "12 >>>f.readline()13 ""
f.flush() 将修改写入到文件中(无需关闭文件)
>>> f.write("hello python!")>>>f.flush()
hello girl!hello boy!hello man!hello python!
f.tell() 获取指针位置
1 >>> f = open("/tmp/test.txt")2 >>>f.readline()3 "hello girl! "4 >>>f.tell()5 12
6 >>>f.readline()7 "hello boy! "8 >>>f.tell()9 23
本文介绍了Python中常见的文件操作方法,包括按行读取、一次性读取全部内容、按列表形式读取、追加写入等,并详细说明了seek、tell及flush方法的使用场景。
2974

被折叠的 条评论
为什么被折叠?



