复习Python的Day19
发布日期:2021-07-01 03:02:54
浏览次数:3
分类:技术文章
本文共 2037 字,大约阅读时间需要 6 分钟。
复习Python的第十九天
习题 20: 函数和文件
先建立一个文件,名为“save.txt”。内容即为作者在代码中给出的那样:
To all the people out there. I say I don't like my hair. I need to shave it off.
The Codes
from sys import argv # 命令行参数解包 script, input_file = argv def print_all(f): print f.read() def rewind(f): f.seek(0) # 将文件指针移至文件开始处def print_a_line(line_count, f): print line_count, f.readline() # 打开目标文件 current_file = open(input_file) print "First let's print the whole file:\n" # 打印全部文件内容 print_all(current_file) # 让我们倒回文件开始,像打字机一样从头开始print "Now let's rewind, kind of like a tape." rewind(current_file) print "Let's print three lines:" # 打印第一行 current_line = 1 print_a_line(current_line, current_file) # 打印第二行 current_line = current_line + 1 print_a_line(current_line, current_file) # 打印第三行current_line = current_line + 1 print_a_line(current_line, current_file)
本节知识
各种文件相关的命令(方法/函数)
close
– 关闭文件read
– 读取文件内容。你可以把结果赋给一个变量readline
– 读取文本文件中的一行truncate
– 清空文件内容write(stuff)
– 将stuff写入文件seek()
– 移动文件指针至某一字节处
让我们试试最后一个方法,在交互式模式下运行:
>>> file = open('save.txt')>>> file<_io.TextIOWrapper name='save.txt' mode='r' encoding='cp936'>>>> print file.readline() # 文件指针移至第一行末尾To all the people out there.>>> print file.readline() # 文件指针移至第二行末尾I say I don't like my hair.>>> print file.readline() # 文件指针移至文件末尾I need to shave it off.>>> print file.readline() # 返回空字符串''>>> file.seek(0) # 将文件指针移至文件开始处0>>> print(file.readline()) # 又打印出第一行To all the people out there.
让我们看一看关于返回的文件对象的文档:
| seek(self, cookie, whence=0, /) | Change stream position. | | Change the stream position to the given byte offset. The offset is | interpreted relative to the position indicated by whence. Values | for whence are: | | * 0 -- start of stream (the default); offset should be zero or positive | * 1 -- current stream position; offset may be negative | * 2 -- end of stream; offset is usually negative | | Return the new absolute position.
whence
:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;0 代表从文件开头开始算起,1 代表从当前位置开始算起,2 代表从文件末尾算起。
该函数会返回新的绝对位置。
本节内容就到这里。
转载地址:https://memcpy0.blog.csdn.net/article/details/79820596 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
关注你微信了!
[***.104.42.241]2024年05月03日 00时21分58秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
对称加密整个过程
2019-05-01
java内存模型
2019-05-01
volatile关键字
2019-05-01
Servlet_快速入门
2019-05-01
Servlet_生命周期方法
2019-05-01
Servlet_体系结构
2019-05-01
Request_原理
2019-05-01
Request_继承体系
2019-05-01
前端权限控制:获取用户信息接口构造数据
2019-05-01
有状态服务和无状态服务
2019-05-01
七牛云存储:断点续传
2019-05-01
字节流复制文本文件【应用】
2019-05-01
字节流复制图片
2019-05-01
其他数字摘要算法实现
2019-05-01
私钥加密私钥解密
2019-05-01
锁的释放流程-ReentrantLock.unlock
2019-05-01
Java判断字符串是否为数字(浮点类型也包括)
2019-05-01
ubuntu opencv-python 安装很慢问题
2019-05-01
MySQL5.7版本修改了my.ini配置文件后mysql服务无法启动问题
2019-05-01
【大数据开发】Java基础 -总结21-Hashmap和HashTable的区别
2019-05-01