2016-06-01 73 views
0

我一直在处理这部分代码,试图得到一个possitive,但无法得到一个。一段时间后发现我的函数“if open in open('users.txt'):”并不是要识别字符串的一部分,因为如果users.txt只包含单词“博拉”。 我的意思是,如果我在user.txt中写入“Bola”,它会给我一个错误。 我设法了解问题,但不知道如何解决它。 使用U.find()尝试,但它并没有提前python:if open in open(example.txt)not reading the string

U=open('users.txt','a+') 
    bola = "Bola" 
    if bola in open('users.txt'): 
     U.close() 
     print("usercid found") 
    else: 
     U.write("[" + str(cid) + "]"+str(m.from_user.first_name)+"\n") 
     U.close() 
     print("no usercid gaaaaa") 
+0

简单地说:你从来没有真正读取文件。首先,无论你喜欢什么方式。 – TigerhawkT3

回答

3

open('users.txt')返回发电机,其列举了文件,不包含该文件内容的字符串的行,因为这样if bola in open('users.txt')会当且仅返回True如果生成的序列中有一个元素与bola匹配。

为了您的使用情况,你要做到以下几点:

if bola in open('users.txt').read(): 
    U.close() 
    print("usercid found") 

open(...).read()将返回一个代表整个文件,因此,如果bola包含在文件中bola in open(...).read()将返回True字符串一个低调,不一定是一条线。

这仍然有一个问题(您的原始代码也有),您泄漏了open创建的文件描述符。为了避免它,你可以做线沿线的:

with open('users.txt') as fr: 
    if bola in fr.read(): 
     U.close() 
     print("usercid found") 
    else: 
     ... 
+0

嘿,这实际上工作,谢谢! 我不是如何文件描述符将帮助我,但我可以稍后阅读。再次感谢 – Bola

+0

这是在文件中查找特定字符串的好方法。 –

0

你找不到你的字符串,因为开放的工作,要么...任何解决方案将apreciated ...

感谢( 'users.txt')返回一个字符串列表,每个字符串都带有一个换行符。最简单的办法是寻找bola = "Bola\n"

或者:

for line in open('file.txt'): 
    if bola == line.rstrip(): 
     print("usercid found") 
     break 
+0

你的意思是它返回每条线如 string1 string2 string3 ??? 有没有办法找到我需要的字符串之间的字符串? – Bola

+0

@DiegoErósteguiNavia,打开('file.txt')将返回像“bola \ n”这样的行,但您会与“bola”进行比较。所以你要么从每一行删除换行符,要么在搜索查询中添加'\ n'。 – kaspersky

0
U=open('users.txt','a+') 
bola = "Bola" 
for line in open('users.txt'): 
    if line.find(bola) >= 0: 
     U.close() 
     print("usercid found") 
    else: 
     U.write("[" + str(cid) + "]"+str(m.from_user.first_name)+"\n") 
     U.close() 
     print("no usercid gaaaaa")