zoukankan      html  css  js  c++  java
  • 笨办法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,有点理解,还要再继续消化一下!

  • 相关阅读:
    第二十天笔记
    第十九天笔记
    第十七天笔记
    第十五天笔记
    第十六天笔记
    第十二天笔记
    数字三角形
    最大子段和与最大子矩阵和
    分组背包
    二维背包
  • 原文地址:https://www.cnblogs.com/p36606jp/p/7648188.html
Copyright © 2011-2022 走看看