前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >习题16:读写文件

习题16:读写文件

作者头像
py3study
发布2018-08-02 11:20:25
2170
发布2018-08-02 11:20:25
举报
文章被收录于专栏:python3python3

文件相关的命令(方法/函数),常用的命令如下

close --- 关闭文件,跟你编辑器的 文件-->保存...一个意思

read --- 读取文件内容,你可以把结果赋给一个变量

readline --- 读取文本文件中的一行

truncate --- 清空文件,请小心使用该命令

write(stuff) --- 将stuff写入文件

write需要接收一个字符串作为参数,从而将该字符串写入文件

使用这些命令做一个简单的文本编辑器吧

练习代码

代码语言:javascript
复制
# coding: utf-8
__author__ = 'www.py3study.com'
from sys import argv
script, filename = argv
print("We're going to erase {}.".format(filename))
print("If you don't want that,hit CTRL-C (^C)")
print("If you do want that, hit RETURN.")
input("?")
print("Opening the file...")
target = open(filename, "w")
print("Truncating the file. GoodBye !")
target.truncate()
print("Now I'm going to ask you for three lines.")
line1 = input("line 1:")
line2 = input("line 2:")
line3 = input("line 3:")
print("I'm going to write there to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally, we close it.")
target.close()

小技巧就是可以让你的脚本一部分一部分地运行起来,也方便排查错误,以此类推,直到整个脚本运行起来为止

跟上个练习一下,在当前目录创建一个test.txt文件

运行命令

python lianxi_16.py test.txt

应该看到的结果

E:\test>python lianxi_16.py test.txt We're going to erase test.txt. If you don't want that,hit CTRL-C (^C) If you do want that, hit RETURN. ? Opening the file... Truncating the file. GoodBye ! Now I'm going to ask you for three lines. line 1:www.py3study.com line 2:py3study.com line 3:py3study I'm going to write there to the file. And finally, we close it. 最后还可以验证一下,test.txt文件,看看里面是否有你写入的内容

图片.png
图片.png

常见问题

为什么'w'要放在括号中?

w是指写入的意思,也就是write

len()函数的功能是什么?

它会以数字的形式返回你传递的字符串长度

最后为什么要close?

打开文件,对应的当然就需要保存文件,在java,C中如果不关闭文件,还会引起内存泄漏,总之一句话对文件操作完后,记得关闭文件

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-11-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档