2016-06-14 71 views
0

我真的很渴望得到這個python代碼的一些幫助。我需要搜索一個變量(字符串),將其返回並將數據與變量數據存在同一行。使用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 

預先感謝您。

+2

您正在尋找字符串列表中的「數字」字符串......您可能想要做的事情如下:'對於行中的行:if number in line .. .' – alfasin

回答

0

它是這樣

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

這是什麼會做的是給你在文本文件中的所有行以列表的形式,然後你可以簡單地打印出列表中的內容...

2

見下面我的變化:

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 
0

如果使用'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