Home > Backend Development > Python Tutorial > Why Does My String Search in Python Text Files Always Return True?

Why Does My String Search in Python Text Files Always Return True?

Linda Hamilton
Release: 2024-12-04 07:03:09
Original
303 people have browsed it

Why Does My String Search in Python Text Files Always Return True?

Search for a String within Text Files

In an attempt to determine the presence of a specific string within a text file, a program may encounter unexpected behavior. To rectify this issue, it's crucial to understand the underlying reason behind the incorrect results.

Original Code:

def check():
    datafile = file('example.txt')
    found = False
    for line in datafile:
        if blabla in line:
            found = True
            break

check()
if True:
    print "true"
else:
    print "false"
Copy after login

Reason for False Results:

The provided code consistently returns True regardless of the string's presence in the file because the evaluation of 'if True' in the following block is not tied to the logic of the preceding loop.

if True:
    print "true"
else:
    print "false"
Copy after login

Python with Open:

An alternative approach to reading a text file is to utilize the 'with' statement in conjunction with the 'open()' function. This method creates a 'file-like' object that automatically handles file closing.

with open('example.txt') as f:
    if 'blabla' in f.read():
        print("true")
Copy after login

Using Memory Mapping:

Another technique for working with text files is memory mapping. This approach reads the entire file into memory as a string-like object, enabling faster access and the possibility of using regular expressions.

import mmap

with open('example.txt', 'rb', 0) as file, \
     mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
    if s.find(b'blabla') != -1:
        print('true')
Copy after login

By following these suggestions, you can accurately search for strings within text files and obtain the expected results.

The above is the detailed content of Why Does My String Search in Python Text Files Always Return True?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template