python 中提取以指定字符开头或指定字符结尾的数据
1、提取以x开头的行
[root@PC1 test]# ls a.txt test.py [root@PC1 test]# cat a.txt u r d s f e a d e x v m e f x e r d z d v [root@PC1 test]# cat test.py ## 提取以x开头的行 #!/usr/bin/python in_file = open("a.txt", "r") out_file = open("result.txt", "w") lines = in_file.readlines() for i in lines: if i.startswith("x"): out_file.write(i) in_file.close() out_file.close() [root@PC1 test]# python test.py [root@PC1 test]# ls a.txt result.txt test.py [root@PC1 test]# cat result.txt x v m
2、提取以x开头或者以e开头的行
[root@PC1 test]# ls a.txt test.py [root@PC1 test]# cat a.txt u r d s f e a d e x v m e f x e r d z d v [root@PC1 test]# cat test.py ## 同时提取以x开头或者以e开头的数据 #!/usr/bin/python in_file = open("a.txt", "r") out_file = open("result.txt", "w") lines = in_file.readlines() for i in lines: if i.startswith("x") or i.startswith("e"): out_file.write(i) in_file.close() out_file.close() [root@PC1 test]# python test.py [root@PC1 test]# ls a.txt result.txt test.py [root@PC1 test]# cat result.txt x v m e f x e r d
3、提取以e和d结尾的数据
[root@PC1 test]# ls a.txt test.py [root@PC1 test]# cat a.txt u r d s f e a d e x v m e f x e r d z d v [root@PC1 test]# cat test.py ## 提取以d或者以e结尾的数据 #!/usr/bin/python in_file = open("a.txt", "r") out_file = open("result.txt", "w") lines = in_file.readlines() for i in lines: if i.endswith("e\n") or i.endswith("d\n"): out_file.write(i) in_file.close() out_file.close() [root@PC1 test]# python test.py [root@PC1 test]# ls a.txt result.txt test.py [root@PC1 test]# cat result.txt u r d s f e a d e e r d
4、提取以x开头或者以e开头同时以x结尾的数据
[root@PC1 test]# ls a.txt test.py [root@PC1 test]# cat a.txt u r d s f e a d e x v m e f x e r d z d v [root@PC1 test]# cat test.py ## 提取以x开头,或者以e开头同时以x结尾的数据 #!/usr/bin/python in_file = open("a.txt", "r") out_file = open("result.txt", "w") lines = in_file.readlines() for i in lines: if (i.startswith("x")) or (i.startswith("e") and i.endswith("x\n")): out_file.write(i) in_file.close() out_file.close() [root@PC1 test]# python test.py [root@PC1 test]# ls a.txt result.txt test.py [root@PC1 test]# cat result.txt x v m e f x