如果语句在python中无法正常工作

时间:2016-06-15 08:18:17

标签: python for-loop

首先,我打开文件并写了一些数字。

writeFile = open("charge_accounts.txt", "w")
writeFile.write("5658845\n")
writeFile.write("4520125\n")
writeFile.write("7895122\n")
writeFile.write("8777541\n")
writeFile.write("8451277\n")
writeFile.write("1302850\n")
writeFile.write("8080152\n")
writeFile.write("4562555\n")
writeFile.write("5552012\n")
writeFile.write("5050552\n")
writeFile.write("7825877\n")
writeFile.write("1250255\n")
writeFile.write("1005231\n")
writeFile.write("6545231\n")
writeFile.write("3852085\n")
writeFile.write("7576651\n")
writeFile.write("7881200\n")
writeFile.write("4581002\n")

writeFile.close()
writeFile = open ("charge_accounts.txt", "r")
print writeFile.read()

现在,我尝试搜索文件中的数字。如果找到数字打印有效输入。但即使输入正确的输入,我的代码也不会打印有效输入。

digit = raw_input('Input seven-digit account number: ')
digit2 = len(str(digit))
digit = str(digit)
if digit2 == 7:
    text = open('charge_accounts.txt', "r")
    for line in text:
        digit3 = line
        print 'here', line, "num", digit, "\n"
        if line in digit:
        print "\n Valid input"

2 个答案:

答案 0 :(得分:0)

每个line字符串的末尾仍然有\n,所以即使行和数字看起来相同,if line in digit:也无效。相反,反过来:

if digit in line:

此外,digit已经是raw_input之后的字符串,因此无需转换它。您应该使用with打开并关闭文件。

digit = raw_input('Input seven-digit account number: ')
if len(digit) == 7:
    with open('charge_accounts.txt') as text:
        for line in text:
            print 'here', repr(line), "num", digit, "\n"
            if digit in line:
                print "\n Valid input"

答案 1 :(得分:0)

这将有效: -

    digit = raw_input('Input seven-digit account number: ')
    digit2 = len(str(digit))
    digit = str(digit)
    if digit2 == 7:
        print 'hello'
        text = open('charge_accounts.txt', "r")
        for line in text:
            digit3 = line
            print 'here', line, "num", digit, "\n"
            if int(line) == int(digit):
                print "\n Valid input"