方验证不起作用

时间:2016-03-03 23:50:14

标签: python python-3.x

我的验证是为了检查我加载到程序中的文件是否是正方形不起作用,我不知道为什么并且想要一些帮助+指导和解释以便我可以学习。

问题是将文件加载到python中,然后检查文件是否为nxn square。

我做错了什么,我该如何解决?

代码:

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


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

我得到了它,但是当我运行程序时,我得到了:

File contents:
---------------
ABC
BAC
CAB
LJ
Incorrect file format
Enter the filename:

这是有效的,但是如何更改程序,以便在文件格式不正确的情况下甚至不打印文件?我试过玩它并且无法解决它。

1 个答案:

答案 0 :(得分:0)

您需要在打印之前致电square()

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