您好,我正在合併兩個單獨的.txt文件並輸出個性化信函的功能。問題是,我可以將我的文本包含在funciton模塊中,並且完美地工作。但是當我嘗試在函數打開它們,以供功能使用我得到這個如何讓我的文件被打開?
錯誤消息:
回溯(最近通話最後一個): 文件「/用戶/ nathandavis9752/CP104/davi0030_a10 /src/q2_function.py「,第25行,在 data = cleanData(q2) 文件」/Users/nathandavis9752/CP104/davi0030_a10/src/q2_function.py「,第17行,在cleanData中 return [item.strip( ).split('\ n \ n')for query.split(' - ')] AttributeError:'file'對象沒有屬性'split'
code:
letter = open('letter.txt', 'r')
q2 = open('q2.txt', 'r')
def cleanData(query):
return [item.strip().split('\n\n') for item in query.split('--')]
def writeLetter(template, variables, replacements):
# replace ith variable with ith replacement variable
for i in range(len(variables)):
template = template.replace(variables[i], replacements[i])
return template
data = cleanData(q2)
print (data)
variables = ['[fname]', '[lname]', '[street]', '[city]']
letters = [writeLetter(letter, variables, person) for person in data]
for i in letters:
print (i)
q2.txt文件:
Michael
dawn
lock hart ln
Dublin
--
kate
Nan
webster st
king city
--
raj
zakjg
late Road
Toronto
--
dave
porter
Rock Ave
nobleton
letter.txt文件:
[fname] [lname]
[street]
[city]
Dear [fname]:
As a fellow citizen of [city], you and all your neighbours
on [street] are invited to a celebration this Saturday at
[city]'s Central Park. Bring beer and food!
請記住閱讀錯誤。重要的部分是最後一部分:'AttributeError:'文件'對象沒有屬性'split'。 – keyser 2015-04-05 23:30:38