Python 3.x AttributeError:“str”对象没有属性“write”

Python 3.x AttributeError:“str”对象没有属性“write”,python-3.x,attributeerror,Python 3.x,Attributeerror,这是一个简单的问题,但有人能帮我让我的代码正常工作吗?错误发生在第9行,错误属性error:'str'对象没有属性'write'。如果有人能帮我解决这个小问题,我将不胜感激 myFile = ("cat2numbers.txt") with open("cat2numbers.txt", "wt") as f: print("Writing to the file: ", myFile) # Telling the user what file they will be writi

这是一个简单的问题,但有人能帮我让我的代码正常工作吗?错误发生在第9行,错误属性error:'str'对象没有属性'write'。如果有人能帮我解决这个小问题,我将不胜感激

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")

谢谢。

看起来您一行写得正确,下一行写得不正确:

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

请尝试将第二行修改为f.write\n,甚至将换行符添加到一个write中,如f.write、.joinmapstr、positions+\n

myFile是字符串,而不是f file对象。你可能想用f.write来代替。请至少发布语法正确的代码;括号不平衡,缺少一个引用。我刚刚意识到我自己和计划现在修复它。