2017-03-06 123 views
-1

我是一个新手我想实现一个代码,如果我键入文本,它会查看文件内部,并会说如果有匹配的东西,如果不匹配任何东西将显示没有记录但是这下面的代码是不能做出正确的输出任何想法非常感谢你提前输入字符串并在一个文件中搜索Python

input = raw_input("Input Text you want to search: ") 
    with open('try.txt') as f: 
     found = False 
     if input in f: 
     print "true" 
     found = True 
     if not found: 
      print('no record!') 
+1

这甚至不会运行,因为缩进没有意义。 – khelwood

回答

0

与执行检查,为了防止从文件中的文本匹配的字符串,你需要阅读的文件:

with open('try.txt') as f: 
    data = f.read() 

然后检查一个字符串的文件中找到,检查是这样的:

if input_ in data: 
    pass 

此外,两个小技巧:

1)正确缩进你的代码。每个缩进级别使用四个空格。

2)不要使用保留关键字来命名变量。而不是输入,使用input_或其他东西。

0

你实际上并没有读取文件,尝试像file_content = f.read(),然后做一个if input in file_content

+0

谢谢你现在的工作:) – lec

0

如果找到或“没有记录!”,则应打印“true”找不到 我没有包含你的布尔型“找到”变量,因为它没有被使用。 首先将文件数据读入“数据”变量作为一个字符串,然后我们在运营商

input = raw_input("Input Text you want to search: ") 

with open('try.txt', 'r') as myfile: 
    data=myfile.read() 

if input in data: 
    print "true" 
else: 
    print('no record!') 
相关问题