write a python function

来源:百度知道 编辑:UC知道 时间:2024/07/02 22:38:52
def file_to_dict(file, str):

''' Return a dictionary that contains the contents of each line in a given open file as a key-value pair. The file contains lines of the form key separator value, where separator is the second parameter of the function. There may be more than one occurrence of the separatoe in the line; the key is before the first one - all others are part of the value string. Both key and value shoud be without leading or trailing whitespace.'''

def file_to_dict(file, str):
afile=open(file,'r')
mydict={}
for line in afile:
a,b=line.split(str,1)
mydict[a.strip()]=b.strip()
return mydict
#here is my test
print file_to_dict('c:test.txt','$')

def file_to_dict(file, str):
__f = open(file,'r')
__res = dict()
__for line in f:
____sl = [x.strip() for x in line.split(str)]
____value = ''.join(sl[1:])
____res[sl[0]] = value
__return res