【问题标题】:Python String Input and Output From .txt来自 .txt 的 Python 字符串输入和输出
【发布时间】:2015-01-02 21:07:22
【问题描述】:

我正在开发一个聊天机器人项目,该项目通过使用 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

对不起,如果问题似乎有点不清楚。

【问题讨论】:

  • 请注意print(line.rsplit('/',1)[0]) 不会打印出/ 之后的所有内容,它会打印出之前 最后一个 / 之前的所有内容。

标签: python if-statement io compare


【解决方案1】:

mem.read()将所有文件作为一个字符串整体读取

您需要使用mem.readlines()。 readlines 将文件作为行列表读取

或者你可以直接遍历文件指针

for x in mem:             # here x is line
    # do your stuff with line here

【讨论】:

    猜你喜欢
    • 2018-03-15
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    相关资源
    最近更新 更多