2017-02-17 105 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")