将单词和位置保存到空文本文件时,文件打错误



我需要编写一个程序,该程序将存储用户输入&他们的职位清单。可以将其保存为一个或两个文件更容易。

在这片代码中,我只将其保存到一个空白文本文件中,尽管经过进一步的重新考虑,以编程的方式进行编程,也许将它们单独保存为两个不同的文件会更容易。

我已经测试了我的代码,并且知道该程序将吸收用户的输入并输出位置,但是我正在努力的部分是文件处理并将其保存到文件中,因为这会输出错误。是否有任何有用的网站可以帮助我解决此问题或一些有用的功能/修改?谢谢。

这是我的代码:

#SUBROUTINES
def saveItem():
    #save an item into a new file
    print("creating a text file with the write() method")
    textfile=open("task2.txt","w")
    for item in words:
        textfile.write(positions)
        textfile.write("n")
    textfile.close()
    print("The file has been added!")

#mainprogram
sentence = input("Write your sentence here ")
words = sentence.split()
positions = [words.index(word) + 1 for word in words]
print (sentence)
print (positions)
saveItem()

#filehandling
file=open("task2.txt", "r" )
#opens a file called "filename.txt" for "reading"
contents = file.read() 
#reads everything in the file into a string called 'contents' 
file.close()
print(contents)
#we have finished with the file now.
a=True
while a:
    print("Press 1 to save the file:n
    1.Save?n:")
    z=int(input())
    if z == 1:
        saveItem()
    else:
        print("incorrect option")

这是Python给出的错误:Trackback(最近的最新电话): 文件" C:task.3.py",第21行,在 saveitem() 文件" C:task.3.py",第7行,在SaveItem中 textfile.write(位置)typeError:必须是str,不列表

我尝试了您的代码,我得到了2个错误

第一个是:解析时出乎意料的EOF

通过在此行中将input更改为raw_input来解决:

sentence = raw_input("Write your sentence here ")

您可以参考以下内容:python意外EOF

第二个:期望角色缓冲区对象

通过将位置转换为这样的字符串来解决:

textfile.write(str(positions))

您也可以参考:TypeError:预期字符缓冲仪

与我合作的。另外,我相信您可能要删除(for item in words)循环,因为它只是重复写每个单词的所有位置。

听起来您只想需要positions列表的字符串表示形式。最简单的方法是将list施加到str

with open("task2.txt","w") as textfile:
    textfile.write(str(positions))

最新更新