Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.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 - Fatal编程技术网

Python 我写在一个文件上,然后读它,但当我再次运行时,它似乎是

Python 我写在一个文件上,然后读它,但当我再次运行时,它似乎是,python,Python,我想写一个文件,上面写着大家好,但每个单词都必须是列表中的一项。这是我的密码。当我运行它时,它什么也不显示,当我第二次运行时,它会按照我的需要逐项显示。但当我点击文本文件时,它会被写入两次 with open('stavanger.txt','r+') as f: # file closes itself with with open as filename command words = ['hello\n','guys\n','how\n', 'are\n','you\n'] f.w

我想写一个文件,上面写着大家好,但每个单词都必须是列表中的一项。这是我的密码。当我运行它时,它什么也不显示,当我第二次运行时,它会按照我的需要逐项显示。但当我点击文本文件时,它会被写入两次

with open('stavanger.txt','r+') as f: # file closes itself with with open as filename command
  words = ['hello\n','guys\n','how\n', 'are\n','you\n']
  f.writelines(words)
  for i in f:
    x=i.rstrip().split(',')#turn text file into list and we seperate list items by comma .
    print(x)

问题是写入文件使用了缓冲区。所以在这一行之后,什么也没有发生。只有缓冲区改变了

实际上,文件仍然没有更改,并且文件指针仍然位于文件的开头。因此,第二次运行代码时,您会看到打印的内容,它将文件指针保留在文件的末尾,只有当缓冲区传递到文件时,您才拥有重复的内容


如果只想写入文件,只需使用
mode='w'

从停止写入的位置开始读取文件。最好先打开文件进行写入,然后再进行读取

像这样的

with open('stavanger.txt', 'w') as f:  # file closes itself with with open as filename command
    words = ['hello\n', 'guys\n', 'how\n', 'are\n', 'you\n']
    f.writelines(words)

with open('stavanger.txt', 'r') as f:
    for i in f:
        x = i.rstrip().split(',')  # turn text file into list and we seperate list items by comma .
        print(x)

您使用
'r+'
模式有什么具体原因吗?