显示文件中包含关键字的所有行。

时间:2012-10-28 00:22:31

标签: python

我正在尝试创建一个程序来读取文本文件并要求用户输入一个单词,程序应该打印包含该行的所有行...

这是我目前的代码:

f = open ("G:/test.txt", "r");     
line = f.readlines()        
find_word = raw_input("Enter word here:")    
if find_word in f:    
    print find_word    
f.close()

2 个答案:

答案 0 :(得分:3)

这应该有效:

在处理文件时使用with语句,因为它会关闭文件。

with open("G:/test.txt") as f:
   final_word=raw_input("Enter word here:")
   for line in f:                #iterate over each line of f
       if final_word in line:    #if final_word in line , then print it
           print line.strip() 

答案 1 :(得分:1)

您的行列表包含以下字词:

['dom\n', 'hello\n', 'world']

注意换行?你需要剥离它们。

line = open("test.txt").read().splitlines()
find_word = raw_input("Enter word here:")    
if find_word in line:    
    print find_word    
相关问题