Freddy-FazBear
Freddy-FazBear

Reputation: 305

Python String Input and Output From .txt

im working on a chatterbot project that mimicks the user by using a txt file to store the inputs and outputs. But i had come across a problem where it wont compare the input to the file correctly.

here are the lines of code:

  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

Sorry if the question seems a little unclear.

Upvotes: 0

Views: 51

Answers (1)

Hackaholic
Hackaholic

Reputation: 19753

mem.read() read all the file as a string as whole

you need to use mem.readlines(). readlines read the file as a list of lines

or you can directly iterate over file pointer

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

Upvotes: 2

Related Questions