• 笨办法17更多文件操作


    源代码如下:

     1 from sys import argv
     2 from os.path import exists
     3 
     4 script, from_file, to_file = argv
     5 
     6 print "Copying from %s to %s" % (from_file, to_file)
     7 
     8 # We could do these two on one line too, how?
     9 input = open(from_file)
    10 
    11 
    12 indata = open(from_file).read()
    13 
    14 print "The input file is %d bytes long" % len(indata)
    15 
    16 print "Does the output file exist? %r" % exists(to_file)
    17 print "Ready, hit RETURN to continue, CTRL-C to abort."
    18 raw_input()
    19 
    20 output = open(to_file, 'w')
    21 output.write(indata)
    22 
    23 print "Alright, all done."
    24 
    25 output.close()
    26 input.close()

    运行结果: 
    这里写图片描述


    加分习题2,写成一行,代码如下:

     1 from sys import argv
     2 
     3 script, from_file, to_file = argv
     4 
     5 """
     6 in_file = open(from_file)
     7 indata = in_file.read()
     8 out_file = open(to_file, 'w')
     9 out_file.write(indata)
    10 """
    11 
    12 open(to_file, 'w').write(open(from_file).read()) 

    但是没弄明白为啥下面这种写法就不用close


    20170916 学习22课时问了师父,因为open的返回值没有变量接收,用完就释放了,所以不需要close,有点理解,还要再继续消化一下!

  • 相关阅读:
    配置数据同步
    NET移动设备开发
    计算两个日期之间的工作日数
    ActionScript3.0程序开发工具
    常用JS积累之获取节点高度(基于浏览器)
    推荐40个优秀的免费CSS工具
    #include语法
    CSS3属性boxshadow使用教程
    CSS元素背景透明
    js获取网页高度
  • 原文地址:https://www.cnblogs.com/p36606jp/p/7648188.html
Copyright © 2020-2023  润新知