I need to write a program which will store a list of words that the user has input & a list of their positions . This can be saved as easier one file or two files.
In this piece of code I've only saved it into one blank text file although on further rethink of this , programming wise maybe it would be easier to save them separately as two different files.
I've tested my code and know that the program will take the user's input and output the positions but the part I'm struggling with is the file handling of it and saving it to the file as this outputs an error. Is there any helpful websites to help me solve this problem or some useful functions/ modifications? Thanks.
Here is my code:
#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")
Here is the error python gives: Traceback (most recent call last): File "C:task2.3.py", line 21, in saveItem() File "C:task2.3.py", line 7, in saveItem textfile.write(positions) TypeError: must be str, not list