Python .txt 的字符串输入和输出
Python String Input and Output From .txt
我正在开发一个聊天机器人项目,该项目通过使用 txt 文件存储输入和输出来模仿用户。但是我遇到了一个问题,它无法正确比较输入和文件。
这里是代码行:
with open('memory.txt', 'r+') as mem:
#memory.txt is where is store the I/O. ex "(input)/(output)" helloinput/hellooutput
for line in mem.read():
#reiterates through each line
if(UI + '/') in line:
#Here is the problem, where the ui being the user input var is not comparing correct to the memory.txt file line.
#(yes) the / is needed for it to work and i have tried to str(UI + '/') but still no luck
print(line.rsplit('/',1)[0])
#this prints out everything after the / character
抱歉,如果问题看起来有点不清楚。
mem.read()
将所有文件作为一个字符串整体读取
您需要使用 mem.readlines()
。 readlines 将文件作为行列表读取
或者您可以直接遍历文件指针
for x in mem: # here x is line
# do your stuff with line here
我正在开发一个聊天机器人项目,该项目通过使用 txt 文件存储输入和输出来模仿用户。但是我遇到了一个问题,它无法正确比较输入和文件。
这里是代码行:
with open('memory.txt', 'r+') as mem:
#memory.txt is where is store the I/O. ex "(input)/(output)" helloinput/hellooutput
for line in mem.read():
#reiterates through each line
if(UI + '/') in line:
#Here is the problem, where the ui being the user input var is not comparing correct to the memory.txt file line.
#(yes) the / is needed for it to work and i have tried to str(UI + '/') but still no luck
print(line.rsplit('/',1)[0])
#this prints out everything after the / character
抱歉,如果问题看起来有点不清楚。
mem.read()
将所有文件作为一个字符串整体读取
您需要使用 mem.readlines()
。 readlines 将文件作为行列表读取
或者您可以直接遍历文件指针
for x in mem: # here x is line
# do your stuff with line here