Python文件操作之简化代码

一朝误入此门中,从此红尘了如空、、、、

程序这条路,当真是路漫漫、、、

这两天找到一本书,名为《笨方法学Python第三版》,全实例,感觉挺好的。需要的点书名下载, 密码:gmpn

今天想说的是习题17,先看书中源码:

 from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# we could do these two on one line too, how?
in_file = open(from_file)
indata = in_file.read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()
out_file = open(to_file, 'w')
out_file.write(indata)
print "Alright, all done."
out_file.close()
in_file.close()

我的代码稍微改了一下,因为作者是要在命令行下运行,而我用的是Eclipse,如下:

 #!/usr/bin/ python
#-*- coding: utf-8 -*-
# file:ex17.py from os.path import exists from_file = 'D:\PythonProject\workspace\Exercise\Ex\ex16_simple.txt'
to_file = 'D:\PythonProject\workspace\Exercise\Ex\ex17_simple.txt' print "Copying from %s to %s" % (from_file,to_file) #We could do these two on one line too,how?
in_file = open(from_file)
indata = in_file.read() print "The input file is %d bytes long" % len(indata) print "Does the output file exist? %r" % exists(to_file)
print "Ready,hit RETURN to continue, CTRL- C to abort."
raw_input() out_file = open(to_file,"w")
out_file.write(indata) print "Alright, all done." out_file.close()
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真是易用,千万别想得太难、、、、

上一篇:数据库管理软件navicate12的激活和安装


下一篇:第5章 Navicat操作MySQL数据库---增删改查