ex17更多的文件操作

ex17

#coding=utf-8

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)

in_file = open(from_file)
indata = in_file.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exist? %r" % exists(to_file) #判断to_file文件是否存在
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()

out_file = open(to_file,'w') #以写入方式打开
out_file.write(indata)

print "Alright, all done."

out_file.close() #关闭文件
in_file.close()

这课的代码多了一句from os.path import exists,导入这个模块是为了判断,exists(stuff)这个实现查找stuff 是否存在的作用,代码其它部分都很简单,如果还是有些地方搞不明白就用作者提供的方法弄懂它

  • 从后向前把代码读一遍
  • 对每行代码进行注释
  • python + 关键字去google
  • 记录自己犯的错误,这个至关重要

在写这课代码后,我犯一个很低级的错误,就中在命令行这样写:python from.txt to.txt 当时程序出错,我还没意识到什么原因呢(呵呵),后来才想起输入python ex17.py from.txt to.txt,我也是对息无语了。

常见问题中有个小思路记一下:

我尝试改短代码的时候,在脚本的结尾处遇到一个关于文件关闭的问题。
你可能做了一些类似这样的事情,比如indata = open(from_file().read(),这样写的话,就不需要在执行关闭操作,当执行完这一行的时候,文件自动就被关闭了。

你可能感兴趣的:(ex17更多的文件操作)