复习Python的Day19
发布日期:2021-07-01 03:02:54
浏览次数:2
分类:技术文章
本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月17日 02时51分29秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
apache 模块编写(c++)
2019-05-02
Json_c++ json api 的个人总结
2019-05-02
提领类型双关的指针将破坏重叠规则——strict-aliasing
2019-05-02
Git常用命令解说
2019-05-02
HTML5 LocalStorage 本地存储
2019-05-02
Ajax中的XMLHttpRequest对象详解
2019-05-02
HTML获取URL传递的参数
2019-05-02
javacript之cookie
2019-05-02
HTML技巧总结
2019-05-02
GDB命令大全
2019-05-02
gdb调试正在运行的进程
2019-05-02
GDB调试子进程
2019-05-02
使用truss、strace或ltrace诊断软件的"疑难杂症"
2019-05-02
联合体union
2019-05-02
Linux命令ldconfig——动态链接库管理命令
2019-05-02
GNU GDB Debugger
2019-05-02
exec函数族
2019-05-02
指针以及内存分配
2019-05-02
做为一个社会的人,不是靠能写多少行代码,代码多么优雅水平多么高来衡量身家的。
2019-05-02