AttributeError:'str'对象没有属性'write'

时间:2017-02-17 09:34:24

标签: python-3.x attributeerror

这是一个简单的问题,但是有人可以帮助我让我的代码工作吗?错误发生在第9行,错误是AttributeError:'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")

谢谢。

1 个答案:

答案 0 :(得分: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")

相关问题