Search code examples
pythonsplitreadlines

The line is splitting at the wrong place


I'm having problem splitting a lines from a '.txt' file.

I want the line to split at the ',' but it splits each character even when the .split() function has a parameter.

Can someone show me what I've done wrong and how it could be fix or even improved.

That would be greatly appreciated

The line was splitting at the correct place before I moved the split() function into the FOR loop, however even when i typed the correct answer it wouldn't recognise it as the correct one, i tried making the answer into a string to be check against but it didn't effect the problem.

python

def main():
  file = open ("Spanish Words Randomized.txt", "r")
  line = file.readline()
  for line in file:
    line.split(",")
    answer = input("What is '" + line[0] + "' in Spanish?:")
    if answer == str(line[1]):
       print("correct")
    elif answer != str(line[1]):
        print("It was",line[1])


main()

These are the first 3 lines of the .txt file

"
A shanty town,Un barrio de chabolas
Managers,Los gerentes
Running water,El agua corriente
"

the expected result should allow me to input what is on the other side of the ',' and say that it's correct


Solution

  • Try this instead:

    def main():
    
        with open ("Spanish Words Randomized.txt", "r") as fin :
            # read the whole file, stripping EOL and filtering the empty lines
            text = [line.strip() for line in fin.readlines() if len(line) > 1]
    
        for line in text :
           q, a = line.split(",")    # need to catch the results of the split()
           answer = input("What is '" + q + "' in Spanish?:")
           if answer == a :
               print("correct")
           else :    # no point to check what we already know
               print("It was", a)
    
    main()