python:if字符串处于打开状态(示例.txt)不读字符串

2024-06-13 20:35:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在处理这部分代码,试图得到一个positive,但无法得到一个。过了一会儿发现我的函数“if bola in open”用户.txt“):”没有尝试标识字符串的某个部分,因为它只会给我一个positive if用户.txt只包含“Bola”一词。 我是说,如果我在里面写“博拉”用户.txt它会给我一个假的。 我设法理解了这个问题,但不知道如何解决它。 尝试使用U.find(),但也不起作用。。。任何解决方案都将受到重视。。。你知道吗

提前谢谢

    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")

Tags: 函数代码用户intxtcloseifopen
3条回答

找不到字符串,因为用户.txt')返回字符串列表,每个字符串都有一个新行。最简单的解决方案是搜索bola = "Bola\n"

或:

for line in open('file.txt'):
    if bola == line.rstrip():
        print("usercid found")
        break
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")

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:
        ...

相关问题 更多 >