Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何通过python创建文本文件_Python_File - Fatal编程技术网

如何通过python创建文本文件

如何通过python创建文本文件,python,file,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

为了创建一个程序,该程序需要接受用户的句子,列出其位置,并识别单词的每个单独位置,然后将位置编号列表保存到一个文件中,我得到了如下信息:

   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)

这是我到目前为止所拥有的,但似乎找不到任何创建任何文件的东西,我真的不知道如何去做,任何关于导入方向的帮助都将不胜感激。

使用带有“w”或“a”访问修饰符的打开功能

e、 g

参考第条-

创建文件的示例

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

编辑:添加模式

如果使用带有“w+”的打开功能,并且没有此类文件,“打开”将创建新文件

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

有关r,r+,w,w+的更多信息

帮助(打开)
或谷歌您忘记提供允许写入的模式字符串。另外,请不要向新的Python程序员演示糟糕的形式;使用
with
语句,而不是显式调用
close
。显式
close
调用只有在交互式解释器中播放时才有意义(其中块会延迟内容的执行,直到您完成块),或者在特定场景中,打开的类似文件的对象是另一个类(或模块)状态的一部分,所以它不是在同一个函数中打开和关闭的。@ShadowRanger,我认为这太过分了。你不可能让一个人一蹴而就。首先学习基础知识,然后努力提高。我相信这一点。另外,我添加的链接也显示了相同的示例。。你认为他们为什么没有在每个例子中提到
?你提供的链接是在交互式解释器中逐行提供的。而且,你还是错的<代码>“r+”
模式仅在文件已经存在的情况下有效(这样做会覆盖打开的字节,而不会附加到现有文件)。因为根本不需要读取权限,所以这里无论是
“w”
还是
“a”
都更有意义(或者在现代Python上,如果您不想覆盖现有文件,则是
“x”
file = open(Max.txt","w+")