使用python在文本文件中搜索术语

使用python在文本文件中搜索术语,python,Python,我真的非常想得到一些关于python代码的帮助。我需要搜索一个变量(字符串),返回它和变量数据所在行的数据 我已经创建了一个变量,然后在文本文件中搜索变量,但是如果在文本文件中找到了变量中包含的数据,则整个文本文件的内容将打印出来,而不是打印出变量数据所在的行 这是我目前的代码,请帮助: number = input("Please enter the number of the item that you want to find:") f = open("file.txt", "

我真的非常想得到一些关于python代码的帮助。我需要搜索一个变量(字符串),返回它和变量数据所在行的数据

我已经创建了一个变量,然后在文本文件中搜索变量,但是如果在文本文件中找到了变量中包含的数据,则整个文本文件的内容将打印出来,而不是打印出变量数据所在的行

这是我目前的代码,请帮助:

number = input("Please enter the number of the item that you want to       find:")
f = open("file.txt", "r")
lines = f.read()
if lines.find("number"):
    print (lines)
else:
    f.close
提前感谢您。

请参见下面我的更改:

number = input("Please enter the number of the item that you want to find:")
f = open("file.txt", "r")
lines = f.read()
for line in lines:  # check each line instead
    if number in line:  # if the number you're looking for is present
        print(line)  # print it
请参见下面我的更改:

number = input("Please enter the number of the item that you want to find:")
f = open("file.txt", "r")
lines = f.read()
for line in lines:  # check each line instead
    if number in line:  # if the number you're looking for is present
        print(line)  # print it
就像

lines_containg_number = [line for line in lines if number in line]
这将以列表的形式为您提供文本文件中的所有行,然后您可以简单地打印出列表的内容…

就像这样

lines_containg_number = [line for line in lines if number in line]

这将以列表的形式为您提供文本文件中的所有行,然后您可以简单地打印出列表的内容…

如果使用“with”循环,则不必关闭文件。这件事将由我们来处理。否则,必须使用f.close()。解决方案:

number = input("Please enter the number of the item that you want to find:")
with open('file.txt', 'r') as f:
    for line in f:
        if number in line:
            print line

如果使用“with”循环,则不必关闭文件。这件事将由我们来处理。否则,必须使用f.close()。解决方案:

number = input("Please enter the number of the item that you want to find:")
with open('file.txt', 'r') as f:
    for line in f:
        if number in line:
            print line

您正在
行列表中查找字符串
“number”
。。。您可能需要执行以下操作:
对于行中的行:如果行中有数字…
您正在
行列表中查找字符串
“number”
。。。您可能需要执行以下操作:
对于行中的行:如果行中有数字…