代码目的:两个文件,有些字符串是相同的,字符串的拆分是通过空格拆分的。我们希望在B文件中找到和A文件相同字符串的行。
用途:有一张成绩表,里面有姓名、学号,各项成绩等信息,然后我们有一个姓名列表,存放在文件A中,通过A我们可以找到对应姓名的信息。
''' search str in file,and print finded line in the file
'''
def str_search_in_file(str, fname):
with open(fname, 'r') as file_obj:
while 1:
line = file_obj.readline()
if line:
line = line.strip()
if (line.find (str,0) >= 0):
print 'found = ',line
else:
break
def find_same_str_in_2file(file1,file2):
with open(file1, 'r') as file_obj:
list1 = file_obj.readlines()
for line in list1:
strlist = line.split(' ')
i=0
#print 'len=', len(strlist)
while (i <len(strlist)):
#print 'find for',strlist[i].strip() #strlist may have slash \n
str_search_in_file(strlist[i].strip(), file2)
i += 1
# file_reader('test.txt')
'''readline() each is oneline
'''
# file_read_use_while('test.txt')
str_search_in_file('lin', 'test.txt')
find_same_str_in_2file('test.txt', 'map.txt')