LKINLKER
LKINLKER

Reputation: 11

Function not working with spaces in file

def square(sq):
    grid = len(sq)
    for line in sq:
        if len(line) != grid:
            raise ValueError


while True:
try: 
    filesname = input("Enter the filename:") + ".txt"
    file = open(filesname,"r")
    readFile = file.readlines()
    file.close()
    thelist = [line.strip() for line in readFile]
    square(thelist)
    print ("File has:")
    print("\n".join(thelist))


except FileNotFoundError: 
    print ("The file name you have entered does not exist. Please try again.")
except ValueError:
    print ("")
    print ("Incorrect file format")
else:
    break

The file I am trying to open is:

A B C
B C A
C A B

I want to open the file and check if it is a square grid and then report back to the user if it is or not. As you can see the file above is a square grid, however my program says it is not.

When I execute this code it keeps saying "incorrect file format". I think it has something to do with the square function and that it doesn't take into consideration the spaces between the letters and I am not sure how to fix this, can anyone help me?

Upvotes: 1

Views: 51

Answers (1)

alexis
alexis

Reputation: 50190

You've got a sound-alike problem:

>>> "A B C\n".split()
['A', 'B', 'C']
>>> "A B C\n".strip()
'A B C'

In other words, use split(), not strip().

Upvotes: 3

Related Questions