标签:
一朝误入此门中,从此红尘了如空、、、、
程序这条路,当真是路漫漫、、、
这两天找到一本书,名为《笨方法学Python第三版》,全实例,感觉挺好的。需要的点书名下载, 密码:gmpn
今天想说的是习题17,先看书中源码:
1 from sys import argv 2 from os.path import exists 3 script, from_file, to_file = argv 4 print "Copying from %s to %s" % (from_file, to_file) 5 # we could do these two on one line too, how? 6 in_file = open(from_file) 7 indata = in_file.read() 8 print "The input file is %d bytes long" % len(indata) 9 print "Does the output file exist? %r" % exists(to_file) 10 print "Ready, hit RETURN to continue, CTRL-C to abort." 11 raw_input() 12 out_file = open(to_file, ‘w‘) 13 out_file.write(indata) 14 print "Alright, all done." 15 out_file.close() 16 in_file.close()
我的代码稍微改了一下,因为作者是要在命令行下运行,而我用的是Eclipse,如下:
1 #!/usr/bin/ python 2 #-*- coding: utf-8 -*- 3 # file:ex17.py 4 5 from os.path import exists 6 7 from_file = ‘D:\PythonProject\workspace\Exercise\Ex\ex16_simple.txt‘ 8 to_file = ‘D:\PythonProject\workspace\Exercise\Ex\ex17_simple.txt‘ 9 10 print "Copying from %s to %s" % (from_file,to_file) 11 12 #We could do these two on one line too,how? 13 in_file = open(from_file) 14 indata = in_file.read() 15 16 print "The input file is %d bytes long" % len(indata) 17 18 print "Does the output file exist? %r" % exists(to_file) 19 print "Ready,hit RETURN to continue, CTRL- C to abort." 20 raw_input() 21 22 out_file = open(to_file,"w") 23 out_file.write(indata) 24 25 print "Alright, all done." 26 27 out_file.close() 28 in_file.close()
看到后面的加分习题,作者说他能一行给写出来。。。就想了想,还真能做到。。。
file(‘D:\PythonProject\workspace\Exercise\Ex\ex17_simple.txt‘,‘wb‘).write(file(‘D:\PythonProject\workspace\Exercise\Ex\ex16_simple.txt‘,‘rb‘).read())
运行成功,只不过是没有任何提示,不大友好,但不得不说Python真是易用,千万别想得太难、、、、
标签:
原文地址:http://www.cnblogs.com/rousi/p/4979967.html