使用python的openDtest01txt r+打开txt文件并且将我们的对话持续记录在文件中
假设我们的对话记录在一个列表中,可以使用以下代码将其写入到文件中:
dialogue = ['Hello!', 'Hi there.', 'How are you?', 'I am doing well, thanks for asking.']
with open('D:test01.txt', 'r+') as file:
file.seek(0) # 将文件指针移到开头
file.truncate() # 清空文件内容
for line in dialogue:
file.write(line + '\n') # 将每一行写入文件
注意,使用'r+'模式打开文件时,需要先将文件指针移到开头,然后清空文件内容,否则新写入的内容会覆盖原有的内容。在写入每一行时,需要在行末添加换行符,否则所有的内容会写在同一行中。
原文地址: https://www.cveoy.top/t/topic/bc3e 著作权归作者所有。请勿转载和采集!