Python:无法检查文件的内容

2024-09-29 02:27:33 发布

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

我想检查一个字符串是否在文件中,但我似乎无法让它工作。你知道吗

file = open("test.txt","r+")

username = 'user'
password = 'password'

if username+password in file:
    print("true")
else:
    print("false")

文件包含:

userpassword

它应该输出'true',因为'username+password'应该等于'userpassword',但是输出是'false',我做错了什么?你知道吗


Tags: 文件字符串intesttxtfalsetrueif
2条回答

您已打开文件,但尚未读取任何内容。尝试使用content = file.readlines()(同时,尽量避免使用file作为变量名-它也是一个内置函数)

_file = open("test.txt","r+")

username = 'user'
password = 'password'

for line in _file.readlines():
    if username+password in file:
        print("true")
    else:
        print("false")
file = open("test.txt","r+").read()

将文件内容返回到file。只需执行file = open("test.txt","r+")就会返回一个类似文件的对象,实际上您必须从对象中读取文件的内容。你知道吗

相关问题 更多 >