习题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()

最新文章

  1. Oracle DBA常用查询
  2. mvn archetype:create报错解决办法
  3. K-D Tree
  4. 如何修改mysql默认的数据库密码
  5. 细谈CSS布局方式
  6. Wordpress模板制作、改造、设计
  7. HDU4528+BFS
  8. 项目知识点.Part3
  9. TypeScript 中的 SOLID 原则
  10. 详解PHP反射API
  11. Spring框架碰壁日常更新
  12. webpack 打包报错:One CLI for webpack must be installed. These are recommended choices, delivered as separate packages
  13. 48-设置tomcat虚拟路径的两种方法(Eclipse、tomcat、IDEA)
  14. Delphi过程和函数中变量的作用域
  15. SVN服务器搭建实录
  16. iframe高度自适应实现方案
  17. Core Foundation 官方文档翻译
  18. html , body , margin , overflow 之大乱战
  19. Debug就是Debug,Release就是Release
  20. MySQL中哈希表

热门文章

  1. safari浏览器中获取指定时间的毫秒数
  2. Jmeter实现百分比业务比例
  3. IO流分类
  4. 泛型(Java 5 开始)
  5. linux IPC 消息队列
  6. web服务nginx和php的相互关系
  7. js设计模式——3.观察者模式
  8. [bzoj2839]集合计数 题解 (组合数+容斥)
  9. 使用ionic来build安卓apk时,报CordovaError: Requirements check failed for JDK 1.8 or greater
  10. 1. USB协议