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
-
4Doesn't save what on to it? You never write anything to or read anything from the files.jonrsharpe– jonrsharpe2016年11月29日 12:36:21 +00:00Commented Nov 29, 2016 at 12:36
-
You are just opening and closing the file0xtvarun– 0xtvarun2016年11月29日 12:36:53 +00:00Commented Nov 29, 2016 at 12:36
-
f.write('This is a test\n') use this to save text inside fileSzymon– Szymon2016年11月29日 12:38:38 +00:00Commented Nov 29, 2016 at 12:38
2 Answers 2
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
TigerhawkT3
49.4k6 gold badges66 silver badges101 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Gábor Erdős
Never knew print had an option to write to file. Good to know! +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
Billy
5,6592 gold badges31 silver badges57 bronze badges
1 Comment
TigerhawkT3
position is a list. You can't directly write that to a file.lang-py