2017-02-17 106 views
-3

这是一个简单的问题,但有人可以帮我让我的代码工作?错误发生在第9行,出现AttributeError错误:'str'对象没有属性'write'。如果有人能够帮助我解决这个小问题,我将非常感激。AttributeError:'str'对象没有属性'写'

myFile = ("cat2numbers.txt") 
with open("cat2numbers.txt", "wt") as f: 
    print("Writing to the file: ", myFile) # Telling the user what file they will be writing to 
    for i in range(9): 
     sentence = input("Please enter a sentence without punctuation ").lower() # Asking the user to enter a sentence 
     words = sentence.split() # Splitting the sentence into single words 
     positions = [words.index(word) + 1 for word in words] 
     f.write(", ".join(map(str, positions))) # write the places to myFile 
     myFile.write("\n") 
     print("The positions are now in the file") 

谢谢。

+0

'myFile'是一个字符串,而不是'f'文件对象。你可能想用'f.write()'来代替。 –

+0

请至少张贴符合语法正确的代码;括号不平衡,并且缺少一个引用。 –

+0

我刚刚意识到我自己并计划现在修复它。 – minmooongie

回答

0

它看起来就像你在正确的一条线,并错误地在接下来的写作:

f.write(", ".join(map(str, positions))) # write the places to myFile 
    myFile.write("\n") 

尝试是第二线固定f.write("\n"),甚至添加换行符在一个写像f.write(", ".join(map(str, positions)) + "\n")