此代码,2处文件,打开,读写,合并。。有区别。
一处可以,一处不可以。分析原因。
------------------------------
#-------------------------------------------------------------------------------
# Name: ex17.py
# Purpose: 更多文件操作.more file op.
# 从一个文件,copy到另一个文件.
# exist()函数,判断文件是否存在.
#
# Author: huanghuan
#
# Created: 14-08-2013
# Copyright: (c) huanghuan 2013
# Licence: <your licence>
#-------------------------------------------------------------------------------
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copy from %s to %s" % (from_file, to_file)
#---------------------------------------------
# we could do these two on one line too, how?
# in_file = open(from_file) # 打开输入文件.
# in_data = in_file.read() # 读入文件.
# 上面2行,合二为一,注意,关闭也要修改.
in_data = open(from_file).read()
#---------------------------------------------
# '读入文件'长度
print "the size of input_file = %d bytes" % len(in_data)
# 判断'输出文件'是否存在.
print "the output_file exist? %r" % exists(to_file)
# 敲入回车,继续;Ctrl+C,终止.
raw_input("hit 'Return' to continue, 'Ctrl-C' to abort.")
#---------------------------------------------------------
out_file = open(to_file,'w') # 打开'输出文件'.
out_file.write(in_data) # 将数据写入'输出文件'.
# 注意这里,如果合二为一,就出错.不能输出到文件.分析原因.
# open(to_file,'w').write(in_data) # 代码,合二为一
#---------------------------------------------------------
print "All done. close files."
# 关闭文件.
out_file.close()
#open(to_file,'w').close()
# in_file.close()
open(from_file).close()
ex_17_in_data.txt内容如下:
-------------------------------
hello ......
**********
goodbye....
hello ......
hello ......
hello ......
hello ......
hello ......
hello ......
hello ......
hello ......
hello ......
hello ......
hello ......
**********
goodbye....
hello ......
hello ......
hello ......
hello ......
hello ......
hello ......
hello ......
hello ......
hello ......
hello ......