python 中提取以指定字符开头、结尾的数据
1、测试数据
root@PC1:/home/test2# cat a.txt
d u s
x e j
z c e
e f a
z x e
w f e
2、提取以z开头的数据
root@PC1:/home/test2# ls a.txt test.py root@PC1:/home/test2# cat a.txt d u s x e j z c e e f a z x e w f e root@PC1:/home/test2# cat test.py ## 提取以z开头的数据 #!/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("z"): out_file.write(i) in_file.close() out_file.close() root@PC1:/home/test2# python test.py root@PC1:/home/test2# ls a.txt result.txt test.py root@PC1:/home/test2# cat result.txt ## 查看结果 z c e z x e
3、同时提取以z和x开头的数据
root@PC1:/home/test2# ls a.txt test.py root@PC1:/home/test2# cat a.txt d u s x e j z c e e f a z x e w f e root@PC1:/home/test2# cat test.py ## 提取以z开头或者以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("z")) or (i.startswith("x")): out_file.write(i) in_file.close() out_file.close() root@PC1:/home/test2# python test.py root@PC1:/home/test2# ls a.txt result.txt test.py root@PC1:/home/test2# cat result.txt ## 查看结果 x e j z c e z x e
4、提取以e结尾的数据
root@PC1:/home/test2# ls a.txt test.py root@PC1:/home/test2# cat a.txt d u s x e j z c e e f a z x e w f e root@PC1:/home/test2# cat test.py ## 提取以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"): out_file.write(i) in_file.close() out_file.close() root@PC1:/home/test2# python test.py root@PC1:/home/test2# ls a.txt result.txt test.py root@PC1:/home/test2# cat result.txt ## 查看结果 z c e z x e w f e
5、同时提取以e结尾或者j结尾的数据
root@PC1:/home/test2# ls a.txt test.py root@PC1:/home/test2# cat a.txt d u s x e j z c e e f a z x e w f e root@PC1:/home/test2# cat test.py ## 同时提取以e结尾或者以j结尾的数据 #/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("j\n")): out_file.write(i) in_file.close() out_file.close() root@PC1:/home/test2# python test.py root@PC1:/home/test2# ls a.txt result.txt test.py root@PC1:/home/test2# cat result.txt ## 查看结果 x e j z c e z x e w f e
6、提取以z开头且以e结尾的数据
root@PC1:/home/test2# ls a.txt test.py root@PC1:/home/test2# cat a.txt z u s x e j z c e e f a z x e w f e root@PC1:/home/test2# cat test.py ## 提取以z开头,且以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("z")) and (i.endswith("e\n")): out_file.write(i) in_file.close() out_file.close() root@PC1:/home/test2# python test.py root@PC1:/home/test2# ls a.txt result.txt test.py root@PC1:/home/test2# cat result.txt ## 查看结果 z c e z x e

浙公网安备 33010602011771号