发布时间:2019-09-21 10:43:17编辑:auto阅读(1312)
我们在平常的工作中有时候需要对摸一个文件进行操作,比如在一个文件的每行前面添加##之类的,在shell中这个需求很简单,用sed单行就能搞定,下面我们来看看一个文件:
[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]#
[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]#
[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
[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中__name__讲解
下一篇: python join 和 split的
47839
46383
37274
34725
29311
25968
24899
19946
19538
18019
5788°
6410°
5925°
5959°
7062°
5908°
5941°
6435°
6402°
7774°