-8

Well the program is supposed to check if the it sees an "ok" next to the email and if it does spit out the email in another txt file.

Input txt file:

.......ng0@gmail.com,ok
.......ad@live.com,fail
.......12@live.com,fail
.......5w@live.com,fail
.......np@gmail.com,ok
.......an@live.com,fail
.......40@excite.com,fail
.......g1@gmail.com,ok

python code is:

readEmails = open("C:\\Users\\Greg\\Desktop\\rewriteEmails.txt","r")
writeEmails = open("C:\\Users\\Greg\\Desktop\\OutputEmails.txt","w")

for line in readEmails:
    subbed = line[-3:]
    if subbed == "ok":
        split = line.split(",")
        writeEmails.write(split[0])
        print("Email Added")
    else:
        print("Error")

The program seems to always go to the else part of the if statement. I'm kinda having a brain fart; i would love your advice.

Jerry Stratton
  • 2,699
  • 19
  • 25
chidog12
  • 61
  • 4

5 Answers5

5

This line: subbed = line[-3:] will give you the last 3 chars of line which can never be 'ok' which is 2 chars.

Will
  • 3,611
  • 5
  • 26
  • 47
2

Instead of depending on string length (you have 3 instead of 2), you can do this line.strip().endswith('ok')

rigel
  • 395
  • 5
  • 11
1

Simply that the last three characters of an "ok" line are ",ok":

>>> line = ".......g1@gmail.com,ok"
>>> line[-3:]
',ok'

edit The previous lines end in a new line, so we get the newline character included instead of the comma:

>>> line = """.......ng0@gmail.com,ok
... """
>>> line[-3:]
'ok\n'

edit ends

Perhaps you should just compare the last two characters:

for line in readEmails:
    subbed = line[-2:]
    #as you were

For a genuine error case, it is often reporting the error, then you can tell what's up easily. Instead of just saying

else:
    print("Error")

you could print out the subbed variable too, and it may have become obvious where the problem lay.

doctorlove
  • 17,477
  • 2
  • 41
  • 57
1

Your problem is this line

subbed = line[-3:]

This returns the following:

ok\n

or

il\n

Thus, your if statement checking if subbed == 'ok' will fail every time.

You can fix this by only taking the last two characters, after stripping the newline:

subbed = line.strip()[-2:]

My original answer didn't account for reading from a file. That answer assumed that the results would be either ,ok or ail. This is not the correct response when reading from a file. The answer above has been modified to show what will be returned and adjusts the solution appropriately.

Andy
  • 43,170
  • 54
  • 150
  • 214
1

You can solve your problem with regex. Here is example for your code.

import re

for line in readEmails:
    subbed = re.match("(?:.*),(\\w+)", line)
    print(subbed.group(1))
    if subbed.group(1) == "ok":
        writeEmails.write(subbed.group(1))
        print("Email Added")
    else:
        print("Error")
Aleksander Monk
  • 2,367
  • 2
  • 15
  • 28