0

Basically I would like to print out a negative statement if a word is not in a file.

import fileinput
import sys

def find(text, file):
    fisier = open(file, "r",  encoding='UTF-8')
    upper = text[0].upper()
    lower = text[0].lower()
    uppertext = upper + text[1:]
    lowertext = lower + text[1:]
    #print(lowertext)
    #print(uppertext)
    for line in fisier.readlines():
        if (uppertext  in line.strip()):
            print(line)
        if (lowertext  in line.strip()):
            print(line)
    if (text not in fisier):
        print(uppertext,"wasn't found in" , file)


def main():
    find("obuz", "catastrofa.txt")
main()

Neither of these work. Despite the word being in the file, it still prints out "text wasn't found in file".

le: more code. fileinput is for something else

john doe
  • 3
  • 3

2 Answers2

0

in file with file being a file descriptor from e.g. open() will give you a list of all the lines in the file. Unless text is meant to match an entire line, including the newline at the end and any leading/trailing whitespace, this is not what you intend. If text is a simple string, and not a regular expression, this is probably what you want:

found=False
for line in file:
    if text in line:
        found=True
if not found:
    print("{} wasn't found in {}".format(text, filename))
twalberg
  • 59,951
  • 11
  • 89
  • 84
0

An idiomatic way for checking presence in a string is using the needle in haystack syntax:

def find_in_file(needle, filepath):
    with open(filepath, 'r') as fh:
        # Case-insensitive search
        if needle.lower() not in fh.read().lower():
            print("%s wasn't found in %s" % (needle.upper(), filepath))

Note on doing case-insensitive search: this is the case for ASCII strings. See this answer and comments for discussion on handling Unicode comparison with Python

Kellen
  • 581
  • 5
  • 18
  • that worked, thank you. also, that's how you do case insensitive search? – john doe May 16 '18 at 19:43
  • @johndoe calling `lower` on both should suffice for most cases, yes. If you're only dealing with ASCII characters then I'd be confident in saying "yes". If unicode normalization is something you are covering, then I'd have to look into it further – Kellen May 16 '18 at 19:45
  • my way (the uppertext and lowertext) isn't good for insesitive search aswell? LE: actually not, it just makes sure that it checks words that start with a capital letter. – john doe May 16 '18 at 19:48
  • @johndoe why would `"foo".upper() == "Foo".upper()` and `"FOO".lower() == "Foo".lower()` not yield the same result (for ASCII characters)? – Kellen May 16 '18 at 19:50