0

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

Dani M
  • 25
  • 1
  • 6
  • You are attempting to write a `list` to the file: `textfile.write(positions)`, but `write` takes a `str`. What is the desired output of `task2.txt`? – Crispin Feb 26 '17 at 10:11
  • task2.txt should have written in the a list of words and a list of the positions for these words . Positions comes as a list as it searches through the words in the sentence and gives positions after each blank space so it can't be a string. Is there a way of solving this? – Dani M Feb 26 '17 at 10:14
  • Step 1 of debugging: Look at the error message (`TypeError: write() argument must be str, not list`). Optional Step 2: Paste error message into google to make sure you understand it. Step 3: Google "save list to file" or "convert list to string" or something similar. And if all that doesn't help and you _really_ need to post a question on SO, at least include the error message. – Aran-Fey Feb 26 '17 at 10:15
  • Here's an example of what task2.txt could hold when the user has input a sentence: ['programming', 'is', 'fun', ' can', 'be', 'hard'] [1, 2, 3, 1, 5, 6, 7] – Dani M Feb 26 '17 at 10:18
  • I've updated the question to show the error message if that is of any help. – Dani M Feb 26 '17 at 10:23
  • also, it's a good idea to use the [`with`](https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects) keyword for opening/closing file handles. – Crispin Feb 26 '17 at 10:27

2 Answers2

1

I tried your code and I got 2 errors

First is: unexpected EOF while parsing

solved by changing input to raw_input in this line:

sentence = raw_input("Write your sentence here ")

you may refer to this: Python unexpected EOF while parsing

Second: expected a character buffer object

solved by converting positions to string like this:

textfile.write(str(positions))

you may refer to this also: TypeError: expected a character buffer object

That worked with me. Plus, I believe you might want to remove the (for item in words) loop cause it just repeats writing all of the positions for every word.

Community
  • 1
  • 1
0

It sounds like you just want a string representation of your positions list. The easiest way to do that is to just cast the list to a str

with open("task2.txt","w") as textfile:
    textfile.write(str(positions))
Crispin
  • 2,070
  • 1
  • 13
  • 16
  • I've updated the code with the string method which works however when I save this to the text file the file has the positions repeated depending on how many words there are in the sentence. Example: [1, 2, 3, 1, 5, 6] [1, 2, 3, 1, 5, 6] [1, 2, 3, 1, 5, 6] [1, 2, 3, 1, 5, 6] [1, 2, 3, 1, 5, 6] [1, 2, 3, 1, 5, 6] As there are 6 words in the sentence but I only want the positions to be saved in the file once. – Dani M Feb 26 '17 at 10:41
  • because the write line is in a for loop. just get rid of the loop (see edit) – Crispin Feb 26 '17 at 10:50