输出文件

时间:2016-11-29 12:33:31

标签: python python-3.x

这是我的代码

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()

它生成文件但不保存任何内容。我做错了什么?

2 个答案:

答案 0 :(得分:6)

你从未以任何方式写过任何文件。你可以通过几种方式做到这一点。由于您已经在使用Python 3的print函数,请尝试使用file参数:

print(UserSen, file=sentext)

...

print(position, file=postext)

答案 1 :(得分:1)

print函数不会写入文件。你需要明确地写信给它。

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

同样地:

postext = open("ThePos.txt", "w")
...
postext.write(str(position))
postext.close()