我想在txt文件中搜索特定的单词并打印整行

时间:2017-11-20 19:39:12

标签: python python-3.x

我的代码目前是:

admin_username_choice = input("Enter the user's username: ")
with open("data.txt") as f:
    line = f.read().split()
for line in f:
    if admin_username_choice in line:
        print(line)
    else:
        print("Incorrect information")

但这打印出来 - 对于f中的行: ValueError:关闭文件的I / O操作。

有人可以告诉我我做错了什么吗?

3 个答案:

答案 0 :(得分:5)

with关闭文件,使其余代码无法访问。您可能想检查缩进。

admin_username_choice = input("Enter the user's username: ")
with open("data.txt") as f:
    line = f.read().split()
    if admin_username_choice in line:
        print(line)
    else:
        print("Incorrect information")

答案 1 :(得分:1)

试试这个

admin_username_choice = input("Enter the user's username: ")
lines='' #just to initialize "lines" out of the with statement 
with open("data.txt") as f:
    lines = f.read().split()
#"f" becomes "lines" here. You will already have closed "f" at this point
for line in lines:
    if admin_username_choice in line:
        print(line)
    else:
        print("Incorrect information")

答案 2 :(得分:1)

您的缩进块已关闭。转到for块时,with语句会关闭文件。这段代码应该做你想要的。

admin_username_choice = input("Enter the user's username: ")
with open("data.txt") as f:
    for line in f:
        if admin_username_choice in line.split():
            print(line)
        else:
            print("Incorrect information")