Answers for "check if text in file python"

2

how to check for a particular word in a text file using python

file = open("search.txt")
    print(file.read())
    search_word = input("enter a word you want to search in file: ")
    if(search_word in file.read()):
        print("word found")
    else:
        print("word not found")
Posted by: Guest on August-10-2020
1

how to check if a string is in a file python

def search_string_in_file(file_name, string_to_search):
    """Search for the given string in file and return lines containing that string,
    along with line numbers"""
    line_number = 0
    list_of_results = []
    # Open the file in read only mode
    with open(file_name, 'r') as read_obj:
        # Read all lines in the file one by one
        for line in read_obj:
            # For each line, check if line contains the string
            line_number += 1
            if string_to_search in line:
                # If yes, then add the line number & line as a tuple in the list
                list_of_results.append((line_number, line.rstrip()))
 
    # Return list of tuples containing line numbers and lines where string is found
    return list_of_results
Posted by: Guest on April-01-2020
2

python read text file look for string

f = open(filename,  "r")
   whattoReturn = "None"
   if strToFind in f.read():
      whattoReturn = strToFind
Posted by: Guest on April-01-2020
0

check if file is txt python

Assuming m is a string, you can use endswith:

if m.endswith('.mp3'):
...
elif m.endswith('.flac'):
...
To be case-insensitive, and to eliminate a potentially large else-if chain:

m.lower().endswith(('.png', '.jpg', '.jpeg'))
Posted by: Guest on May-06-2021

Code answers related to "check if text in file python"

Python Answers by Framework

Browse Popular Code Answers by Language