[关闭]
@mdjsjdq 2016-01-07T14:57:11.000000Z 字数 1058 阅读 1689

实用Python脚本

Python


copy_file.py

用法 copy_files.py from_file to_file,就可以把文本(.txt 文件格式)文件复制

  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename : copy_file.py
  4. import sys
  5. from os.path import exists # 这样的py脚本不太好
  6. script,from_file,to_file = sys.argv
  7. print "Cpoying from %s to %s." % (from_file,to_file),"\n"
  8. print """
  9. I wanna to use Pyhton to copy files like from_file to to_file. "\n"
  10. """
  11. in_file = open(from_file)
  12. in_data = in_file.read() # 先打开才能读取,最后还要关闭
  13. print "The input file is %d bytes long" %len(in_data),"\n"
  14. print "Does the outfiles exist? %r" %exists(to_file) #这段代码比较有意思,很重要\
  15. # 要是文件不存在就创建一个文件
  16. print "Ready please press Enter to contiue,Ctrl + C to abort.","\n"
  17. raw_input()
  18. to_file = open(to_file,"w")
  19. to_file.write(in_data)
  20. print "Aright ,all done."
  21. to_file.close()
  22. in_file.close()

cat.py

类似于Unix\Linux上的cat命令,可以查看一个文本文件的内容,用法:cat.py flie

  1. #!/usr/bin/python
  2. # coding = utf-8
  3. # Filename: cat.py
  4. import sys
  5. def readfile(filename):
  6. '''Print a file to the standard output.'''
  7. f = file(filename)
  8. while True:
  9. line = f.readline()
  10. if len(line) == 0:
  11. break
  12. print line, # notice comma(注意逗号)
  13. f.close()
  14. for filename in sys.argv[1:]:
  15. readfile(filename) # 本程序完全没问题
  16. #是sys.argv[1:]代表着其中的非本程序的文件,要是本程序的问你安默认是sys.argv[0:]
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注