python模擬sed在每行添加##

     咱們在日常的工做中有時候須要對摸一個文件進行操做,好比在一個文件的每行前面添加##之類的,在shell中這個需求很簡單,用sed單行就能搞定,下面咱們來看看一個文件:
python

[root@host-192-168-209-128 py-sed]# cat a.txt
this is a text
this is use for python
this is also user for sed
this is a end test file
[root@host-192-168-209-128 py-sed]#
用sed的單行命令來搞定這個需求很簡單,看下代碼:
[root@host-192-168-209-128 py-sed]# sed 's/^/##/g' a.txt
##this is a text
##this is use for python
##this is also user for sed
##this is a end test file
[root@host-192-168-209-128 py-sed]#

看看,果真夠強大的sed啊,下面我來給你們介紹介紹如何用python實現這個有時候常常須要的操做,直接上代碼了:
[root@host-192-168-209-128 py-sed]# cat a.py
#!/usr/bin/env python

with open('a.txt') as f:
       con=f.readlines()
       for i in range(0,len(con)):
               print "###"+con[i].rstrip('\n')
代碼實在很簡單,看看效果如何吧:
[root@host-192-168-209-128 py-sed]# python a.py
###this is a text
###this is use for python
###this is also user for sed
###this is a end test file

呵呵,效果出來了吧,可是稍有缺陷,這個須要操做的對象文件咱們是寫死在代碼裏面的,如何把文件名做爲參數傳遞給腳本呢,咱們須要修改,以實現以下幾個功能:
1. 須要把操做的文件做爲參數傳給腳本
2.須要對操做的對象進行判斷,是否存在
3.若是腳本運行錯誤,須要有友好的提示效果
基於以上的需求,給出代碼的最終版本,代碼以下:

[root@host-192-168-209-128 py-sed]# cat tou.py
#!/usr/bin/env python
'''
edit by qhz
Email : world77@163.coom
This scrip to add "###" at every line for file

'''
def usage():
       print   '''
===============================================
This script to add "###" at every line for file
Use Example:
python script.py file
===============================================
'''
import sys
import os
if len(sys.argv) == 2:
        if os.path.isfile(sys.argv[1]):
                with open(sys.argv[1]) as f:
                       con=f.readlines()
                       for i in range(0,len(con)):
                              print '###'+con[i].strip('\n')
      else:
                print "==============================================="
                 print "Your input file name is not exit or not correct"
                 print "Please try again ,bye ..."
                 print "==============================================="
else:
          usage()
          exit()
[root@host-192-168-209-128 py-sed]#

下面來看看各類狀況和效果:
[root@host-192-168-209-128 py-sed]# python tou.py

===============================================
This script to add "###" at every line for file
Use Example:
python script.py file
===============================================

[root@host-192-168-209-128 py-sed]# python tou.py a.tx
===============================================
Your input file name is not exit or not correct
Please try again ,bye ...
===============================================
[root@host-192-168-209-128 py-sed]# python tou.py a.txt
###this is a text
###this is use for python
###this is also user for sed
###this is a end test file
[root@host-192-168-209-128 py-sed]#


    好了,此次的python介紹就到這裏,我將爲你們陸續模擬一些sed的簡單功能,但願你們能喜歡
相關文章
相關標籤/搜索