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+'
模式有什么具体原因吗?