加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python读写txt文件

发布时间:2020-12-20 10:24:43 所属栏目:Python 来源:网络整理
导读:整理平常经常用到的文件对象方法: f.readline()?? 逐行读取数据 方法一: 1 f = open(‘/tmp/ test.txt‘) 2 f.readline() 3 ‘hello girl! n‘ 4 f.readline() 5 ‘hello boy! n‘ 6 f.readline() 7 ‘hello man! ‘ 8 f.readline() 9 ‘‘ 方法二: 1 fo

整理平常经常用到的文件对象方法:

f.readline()?? 逐行读取数据
方法一:

1 >>> f = open(‘/tmp/test.txt‘)
2 >>> f.readline()
3 ‘hello girl!n‘
4 >>> f.readline()
5 ‘hello boy!n‘
6 >>> f.readline()
7 ‘hello man!8 >>> f.readline()
9 ‘‘

方法二:

 1 >>> for i in open(‘/tmp/test.txt‘):
 2 ...   print i
 3 ...
 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!n‘,‘hello boy!n‘,‘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!n‘,‘hello man!‘]
 4 >>> f.close()
 5 >>>
 6 >>> f = open(‘/tmp/test.txt‘)
 7 >>> f.next()
 8 ‘hello girl!n‘
 9 >>> f.next()
10 ‘hello boy!n‘
11 >>> f.next()
12 ‘hello man!13 >>> f.next()
14 Traceback (most recent call last):
15 File "<stdin>",line 1,in <module>
16 StopIteration

f.writelines()?? 多行写入

 1 >>> l = [‘nhello dear!‘,‘nhello son!‘,‘nhello baby!n‘]
 2 >>> f = open(‘/tmp/test.txt‘,‘a‘)
 3 >>> f.writelines(l)
 4 >>> f.close()
 5 [[email?protected] 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!n‘
 4 >>> f.readline()
 5 ‘hello boy!n‘
 6 >>> f.readline()
 7 ‘hello man!n‘
 8 >>> f.readline()
 9 ‘ ‘
10 >>> f.close()
11 >>> f = open(‘/tmp/test.txt‘,‘r+‘)
12 >>> f.read()
13 ‘hello girl!nhello boy!nhello man!n‘
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!n‘
 8 >>> f.readline()
 9 ‘hello boy!n‘
10 >>> f.readline()
11 ‘hello man!n‘
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!n‘
4 >>> f.tell()
5 12
6 >>> f.readline()
7 ‘hello boy!n‘
8 >>> f.tell()
9 23

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读