0

This is my code

sentext = open("urSentence.txt", "w")
UserSen = input("Enter your sentence of your choice, ")
print (UserSen)
sentext.close()
postext = open("ThePos.txt", "w")
listSplit = UserSen.split()
X = {} #this will make the words in a sentence assigned to a number
position=[]
for i,j in enumerate(listSplit): #"i" will count how many words there are in the sentence
 if j in X:
 position.append(X[j])
 else:
 X[j]=i
 position.append(i)
print (position)
postext.close()

It makes the files but it doesn't save anything in them. What am I doing wrong?

Brad Larson
170k45 gold badges401 silver badges574 bronze badges
asked Nov 29, 2016 at 12:33
3
  • 4
    Doesn't save what on to it? You never write anything to or read anything from the files. Commented Nov 29, 2016 at 12:36
  • You are just opening and closing the file Commented Nov 29, 2016 at 12:36
  • f.write('This is a test\n') use this to save text inside file Commented Nov 29, 2016 at 12:38

2 Answers 2

6

You never wrote to any file in any way. You can do that in a few ways. Since you're already using what looks like Python 3's print function, try the file parameter:

print(UserSen, file=sentext)
...
print(position, file=postext)
answered Nov 29, 2016 at 12:38
Sign up to request clarification or add additional context in comments.

1 Comment

Never knew print had an option to write to file. Good to know! +1
1

The print function won't write to the file. You need to explicitly write to it.

sentext = open("urSentence.txt", "w")
UserSen = input("Enter your sentence of your choice, ")
sentext.write(UserSen)
sentext.close()

and similarly:

postext = open("ThePos.txt", "w")
...
postext.write(str(position))
postext.close()
answered Nov 29, 2016 at 12:37

1 Comment

position is a list. You can't directly write that to a file.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.