码迷,mamicode.com
首页 > 其他好文 > 详细

笨办法17更多文件操作

时间:2017-10-10 23:22:47      阅读:318      评论:0      收藏:0      [点我收藏+]

标签:print   span   imp   color   file   long   ==   tle   ext   

源代码如下:

 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,有点理解,还要再继续消化一下!

笨办法17更多文件操作

标签:print   span   imp   color   file   long   ==   tle   ext   

原文地址:http://www.cnblogs.com/p36606jp/p/7648188.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!