python 读取文件的常用方法

[root@localhost hejoy]# cat readfile.py
#/usr/bin/env python
#-*-coding:UTF-8-*-

'''
练习读文件,获取关键语句
2017-04-14 09:33
hejoy
'''

import sys
import types

"""读取文件的常用方法"""
def methodone():
fd = open("/home/userhome/weihengjun/20170124.txt")
try:
for line in fd.readlines():
print line
except IOError:
print e
finally:
fd.close()
def methodtwo():
try:
for line in open("/home/userhome/weihengjun/20170124.txt"):
print line
except IOError:
print e

'''
检查数据中是否含有指定的字符,然后输出;
find的用法,如果不含有指定的字符,则返回对应的索引,否则返回-1

'''

def checkstring():
fd = open("/home/userhome/weihengjun/20170123.txt")
for line in fd.readlines():
aa=line.find("2")
if aa == -1:
pass
else:
print "Is Here "+line

def main():
# methodtwo()
checkstring()

if __name__=='__main__':
main()

 

 

[root@localhost hejoy]# python readfile.py
Is Here ÿþ18269751

Is Here 150211782

Is Here 177933502

Is Here 15021267

Is Here 18040824

Is Here 13990244

Is Here 18930298

posted @ 2017-04-14 09:42  David---wei  阅读(802)  评论(0编辑  收藏  举报