方块验证不起作用

2024-09-28 19:00:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我的验证,以检查我加载到程序中的文件是一个正方形或不工作,我不知道为什么,并希望一些帮助+指导和解释,以便我可以学习。你知道吗

问题是将一个文件加载到python中,然后检查该文件是否是nxn正方形。你知道吗

我做错了什么?我该如何修复它?你知道吗

代码:

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:

这是可行的,但是我如何改变程序,使它甚至不打印出文件,如果它不是在正确的格式?我试过玩弄它,但弄不明白。你知道吗


Tags: 文件the程序linefilenamefileprintenter
1条回答
网友
1楼 · 发布于 2024-09-28 19:00:35

打印前需要调用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

相关问题 更多 >