《笨办法学python》源码 Ex17.py

此代码,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 ......




转载于:https://my.oschina.net/darkforce/blog/152704

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值