zoukankan      html  css  js  c++  java
  • Python文件操作之简化代码

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

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

    这两天找到一本书,名为《笨方法学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:PythonProjectworkspaceExerciseExex16_simple.txt'
     8 to_file = 'D:PythonProjectworkspaceExerciseExex17_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()
    View Code

    看到后面的加分习题,作者说他能一行给写出来。。。就想了想,还真能做到。。。

    file('D:PythonProjectworkspaceExerciseExex17_simple.txt','wb').write(file('D:PythonProjectworkspaceExerciseExex16_simple.txt','rb').read())
    View Code

    运行成功,只不过是没有任何提示,不大友好,但不得不说Python真是易用,千万别想得太难、、、、

  • 相关阅读:
    2008年秋季毕业设计总体安排
    2008秋季计算机软件基础0903课堂用例(1)
    收藏:微软新技术不断,开发者如何面对?
    2008秋季计算机软件基础0901课堂用例
    2008秋季计算机软件基础0908课堂用例(1)
    WebBrows仿造Cookie
    ScriptCase价格调整通知
    JavaMail API简介
    Spring攻略学习笔记(3.05)重用切入点定义
    verletjs:超酷的开源JavaScript物理引擎
  • 原文地址:https://www.cnblogs.com/rousi/p/4979967.html
Copyright © 2011-2022 走看看