Python在txt文件中搜索输入 [英] Python search for input in txt file

查看:51
本文介绍了Python在txt文件中搜索输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的脚本运行时,它要求输入.然后检查该输入以查看它是否在文本文件中.如果是,则打印文本.我下面的代码是我所拥有的,但它似乎不起作用,任何帮助将不胜感激!

When my script is run, it asks for an input. That input is then checked to see if it's in a text file. If it is, text is printed. The code I have below is what I have but it doesn't seem to be working, any help would be greatly appreciated!

discordname = input("What's your discord name?: ")
file = open('rtf.txt')
for line in file:
    line.strip().split('/n')
    if line.startswith(discordname):

        file.close()
        print("works")

推荐答案

表达式

line.strip().split('\n')

不会改变绑定到名称 line 的信息,该名称保持不变.相反,它返回一个新值.您需要将该新值绑定到一个名称才能使用它.这个例子可能有帮助:

is not mutating the information bound to the name line, which remains unchanged. Instead it returns a new value. You need to bind that new value to a name in order to use use it. This example might help:

In [1]: a = "  v  "

In [2]: a.strip()
Out[2]: 'v'

In [3]: a
Out[3]: '  v  '

In [4]: b = a.strip()

In [5]: a
Out[5]: '  v  '

In [6]: b
Out[6]: 'v'

然后 split('\n')(注意你可能想要 \ 而不是 /)进一步返回一个 split 子串列表按换行符.请注意,这不是很有用,因为 for line in file: 已经分行了,所以列表最多只有一个元素,所以你应该省略它.

Then split('\n') (note that you probably want \ instead of /) further returns a list of substrings split by newlines. Note that this is not very useful because for line in file: already splits over lines so the list would have one element at most, and so you should omit it.

这篇关于Python在txt文件中搜索输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆