- 练习题2
编写一段代码以完成文件的定位读取
要求:
在python用户目录下创建python06基础班文件夹
在此文件夹中建立read.txt文件。
在此文件中写入"hello world! hello python!hello everyone!"
打开文件,读取5个字符。
查找当前位置,并格式化输出。
把指针重新定位到文件的开头读取10个字符串。
关闭文件
在代码中指定Python解释器。
不要出现中文乱码。
参考代码:
1 #! /usr/bin/python3
2 #coding=utf-8
3
4 f = open("./read.txt", “r+”)
5
6 str = f.read(5)
7
8 print (“读取的字符串是:%s”%str)
9
10 #查找当前位置
11 ps = f.tell()
12 print (“当前位置:%s”%ps)
13
14 #把指针重新定位到文件开头
15 position = f.seek(0,0)
16
17 str = f.read(10)
18
19 print (“重新读取字符串:%s”%str)
20
21 #关闭文件
22 f.close()
python_Daily practice (每日一练) 86
最新推荐文章于 2020-12-08 06:32:46 发布