Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String file.read()在字符串比较中无法正常工作_String_Python 3.x_Io_Comparison - Fatal编程技术网

String file.read()在字符串比较中无法正常工作

String file.read()在字符串比较中无法正常工作,string,python-3.x,io,comparison,String,Python 3.x,Io,Comparison,堆栈溢出 我一直在尝试获取以下代码来创建一个.txt文件,在其上写入一些字符串,然后打印一些消息(如果该字符串在文件中)。这只是一个更复杂项目的研究,但即使考虑到它的简单性,它仍然不起作用 代码: 这个函数总是跳过if,就好像文件中没有“wololo”一样,即使我一直在检查它并且它正确地在那里 我不确定到底是什么问题,我花了很多时间到处寻找解决方案,但都没有用。这个简单的代码可能有什么错误 哦,如果我要在一个更大的.txt文件中搜索字符串,使用file.read()是否仍然是明智的 谢谢 写入文

堆栈溢出

我一直在尝试获取以下代码来创建一个.txt文件,在其上写入一些字符串,然后打印一些消息(如果该字符串在文件中)。这只是一个更复杂项目的研究,但即使考虑到它的简单性,它仍然不起作用

代码:

这个函数总是跳过if,就好像文件中没有“wololo”一样,即使我一直在检查它并且它正确地在那里

我不确定到底是什么问题,我花了很多时间到处寻找解决方案,但都没有用。这个简单的代码可能有什么错误

哦,如果我要在一个更大的.txt文件中搜索字符串,使用file.read()是否仍然是明智的


谢谢

写入文件时,光标将移动到文件末尾。如果要从远处读取数据,必须将光标移动到文件的开头,例如:

file = open("txt.txt", "w+")
file.write('wololo')

file.seek(0)
if "wololo" in file.read():
    print ("ok")
file.close() # Remember to close the file

如果文件很大,则应该考虑逐行地对文件进行迭代。这将避免整个文件存储在内存中。还考虑使用上下文管理器(<代码>使用< /COD>关键字),这样您就不必自己显式地关闭文件。

with open('bigdata.txt', 'rb') as ifile: # Use rb mode in Windows for reading
    for line in ifile:
        if 'wololo' in line:
            print('OK')
    else:
        print('String not in file')
with open('bigdata.txt', 'rb') as ifile: # Use rb mode in Windows for reading
    for line in ifile:
        if 'wololo' in line:
            print('OK')
    else:
        print('String not in file')