如何通过python创建文本文件

时间:2016-09-27 11:32:55

标签: python file

想要创建一个需要接受用户句子的程序,列出其位置,并识别单词的每个位置,然后将位置编号列表保存到文件中,我已经达到了:

   text = input('Please type your sentence: ')
sentence = text.split()
word= input('Thank-you, now type your word: ')

    if word in sentence:
            print ('This word occurs in the places:', sentence.index(word)+1)

elif word not in sentence:
        print ('Sorry, '+word+' does not appear in the sentence.')


text=text.lower()
words=text.split()
place=[]

for c,a in enumerate(words):
    if words.count(a)>2 :
    place.append(words.index(a+1))
    else:
    place.append(c+1)

print(text)
print(place)

这是我到目前为止所做的,但似乎无法找到任何创建任何文件的内容,我真的不知道如何去做,任何有关前进方向的帮助都会很多赞赏。

3 个答案:

答案 0 :(得分:0)

将“打开”功能与“' w'或者' a'访问修饰符。

e.g。

fo = open("foo.txt", "w")

答案 1 :(得分:0)

如果你使用open函数" w +"并且没有这样的文件"打开"将创建一个新文件。

file = open(Max.txt","w+")

有关r,r +,w,w + ...... here

的更多信息

答案 2 :(得分:-1)

参阅文章 - File Operation In Python

创建文件的示例

f = open('file_path', 'w')
f.write('0123456789abcdef')
f.close()

编辑:添加模式

相关问题