笨办法学Python记录--习题15-17 开始读写文件啦
2024-09-07 04:53:22
习题15 - 17
打开并读流程:
from sys import argv
script,filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
txt.close()
对文件操作有用的方法:
close – 关闭文件。跟你编辑器的文件-> 保存.. 一个意思。
• read – 读取文件内容。你可以把结果赋给一个变量。
• readline – 读取文本文件中的一行。
• truncate – 清空文件,请小心使用该命令。
• write(stuff) – 将stuff 写入文件。
写了两个小练习,问题记录:target.read()需要加上print才可以打印出来;target.write(line1+'\n'+line2+'\n')方式能把每行line逐一输出;文件读写完毕后要close!
这个小程序有用,作用是将一个文件copy到另外一个文件中。亮点:len(xx)获取变量中内容的长度;print "Does the output file exist? %r" % exists(to_file)
#将一个文件copy到另外一份文件中
from sys import argv
from os.path import exists script, from_file, to_file = argv print "Copying from %s to %s" % (from_file,to_file) input = open(from_file) indata = input.read() print "The input file is %d bytes long" % len(indata) #len(indata) 求长度的函数 print "Does the output file exist? %r" % exists(to_file) #如果为TRUE,则覆盖;如果为False,则新建一个
print "Ready, hit RETURN to continue,ctrl-c to abort.",raw_input() output = open(to_file, 'w') #必须开启写权限
output.write(indata) #把input内容写进去
print "Alright, all done" output.close() # to double check output
output1 = open(to_file)
print output1.read()
output1.close()
input.close()
最新文章
- Oracle DBA常用查询
- mvn archetype:create报错解决办法
- K-D Tree
- 如何修改mysql默认的数据库密码
- 细谈CSS布局方式
- Wordpress模板制作、改造、设计
- HDU4528+BFS
- 项目知识点.Part3
- TypeScript 中的 SOLID 原则
- 详解PHP反射API
- Spring框架碰壁日常更新
- webpack 打包报错:One CLI for webpack must be installed. These are recommended choices, delivered as separate packages
- 48-设置tomcat虚拟路径的两种方法(Eclipse、tomcat、IDEA)
- Delphi过程和函数中变量的作用域
- SVN服务器搭建实录
- iframe高度自适应实现方案
- Core Foundation 官方文档翻译
- html , body , margin , overflow 之大乱战
- Debug就是Debug,Release就是Release
- MySQL中哈希表