How to search within a text file from a users input than print it using python?

python read text file line by line
python write to text file
how to take input from text file in python
python write to file
python read local file
with open python 3
python print to file
python write variable to file

I am having troubles trying to read multiple lines within a text file using python. My issue is, taking a users specific input and finding that piece of text and printing it out with multiple lines following it. I am trying to keep this within a while function by using elif to continue this part. This code is to take a users U.S State that was inputted and print that state following with the capitol of that state and state bird. This is done by reading in a text file containing the information of all 50 states. This is the code that I am currently working with. This is a small part of a menu that I am working on.

 elif x == "2":
    f = open("States and Capitals.txt", "r")
    x = input("Enter the state you would like to search: ") 
    searchlines =
    for x, line in enumerate(searchlines):
        if x in line:
            for l in searchlines[i:i+3]: print l,

Example of Text file:


Capital: Montgomery

State Bird: Yellowhammer

State Flower: Camellia


Capital: Juneau

State Bird: Willow Ptarmigan

State Flower: Forget Me Not


Capital: Phoenix

State Bird: Cactus Wren

State Flower: Saguaro Cactus Blossom

Try this. You can first split your file input into a list with the split() function, which in this case is using "\n" or newline as a delimiter. Then you just print the next 3 lines from the index or your found string (if it exists). Here I am assuming you want to print the state, the capital, the bird, and the flower (4 lines total).

elif x == "2":
    f = open("States and Capitals.txt", "r")
    x = input("Enter the state you would like to search: ") 
    searchlines ="\n")
    if x in searchlines:
        index = searchlines.index(x)
        for i in range(4):

If you want to exclude the State from the output because it is possibly redundant, then you can make the following minor alteration:

elif x == "2":
    f = open("States and Capitals.txt", "r")
    x = input("Enter the state you would like to search: ") 
    searchlines ="\n")
    if x in searchlines:
        index = searchlines.index(x)
        for i in range(1,4):

Secret Recipes of the Python Ninja: Over 70 recipes that uncover , Over 70 recipes that uncover powerful programming tactics in Python Cody Jackson. -m <module>: This option causes Python to search sys.path for the indicated so anything from the user's keyboard to a file can be used as the input method. Hence, any sort of file can be used as input, ranging from a normal text file to a� This guide on Python input and output lets you know how to get input from the user, files, and display output on the screen, console, or write it into the file. Goals of this article: Learn how to take input from a user and system In Python. Accept an integer, float, character, and string input from a user.

You can use this code

f = open("States and Capitals.txt", "r")
x = input("enter value to search : ") 
searchlines =

7. Input and Output — Python 3.8.4rc1 documentation, (A third way is using the write() method of file objects; the standard output file can be Often you'll want more control over the formatting of your output than simply printing Inside this string, you can write a Python expression between { and } When writing in text mode, the default is to convert occurrences of \n back to� Consider the following problem: Prompt the user for two numbers, and then print out a sentence stating the sum. For instance if the user entered 2 and 3, you would print ‘The sum of 2 and 3 is 5.’ You might imagine a solution like the example file, shown below. There is a problem.

I think something like this may work. The result of this is you will get the variable output that has the line in it you want. You can then print that.

elif x == "2":
    state= input("\nPlease enter a State.\n")
    with open("States and Capitals.txt", "r") as f:
        for line in f:
            if state.lower() in line.lower(): output=line

25.2. doctest — Test interactive Python examples — Python 2.7.18 , To check that a module's docstrings are up-to-date by verifying that all To write tutorial documentation for a package, liberally illustrated with input-output examples. Pass -v to the script, and doctest prints a detailed log of what it's trying, and prints a File "./example.txt", line 14, in example.txt Failed example: factorial(6)� There are times with Python when you need to locate specific information in a string. For example, you may want to know whether a string contains the word Hello in it. One of the essential purposes behind creating and maintaining data is to be able to search it later to locate specific bits of information. …

Here's a way to read the file three lines at time and prints the data from the state it finds that matches (if any):

from itertools import zip_longest

# See
def grouper(iterable, n, fillvalue=None):
    ''' Collect data into fixed-length chunks or blocks. '''
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

target_state = input('Please enter a state name: ')

with open('States and Capitals.txt', 'r') as file:
    for group in grouper(file, 3, ''):  # Read file three lines at a time.
        state, capital, bird = map(str.rstrip, group)  # Remove newlines.
        if state == target_state:
            print(f'State: {state}, Bird: {bird}')
            break  # All done.
        print(f'Error: No state found named {target_state}')

Sample output:

State: Kansas, Bird: Western Meadowlark

1.10. Input and Output — Hands-on Python Tutorial for Python 3, For instance if the user entered 2 and 3, you would print 'The sum of 2 and 3 is 5.' You might imagine a solution like the example file , shown below. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files.

Opening files and reading from files, The basic pattern of opening and reading files in Python; How to open a file – an interactive myfile = open("example.txt") for line in myfile: print(line) myfile.close (). (Note: If (most recent call last) <ipython-input-1-4234adaa1c35> in <module >() ----> 1 myfile Well, we can do a lot more with files than just read() from them. An important part of user input is input validation – checking that the input supplied by the user makes sense. For example, you might require that a particular input is a number between some minimum and maximum values, or that it's a DNA sequence without ambiguous bases, or that it's the name of a file that must exist.

Automating common tasks on your computer, For example, when you open a file for reading, Python looks for it in the current directory. import os >>> cwd = os.getcwd() >>> print cwd /Users/csev We check each file to see if it ends with ".txt" and then count the number of files through to look for files that are more than one line long and show the contents of the file. Modifying a list isn’t very easy when you don’t know what the list contains. The ability to search a list is essential if you want to make maintenance tasks easier. The following steps help you create an application that demonstrates the ability to search a list for specific values. Open a Python File window.

Python User Input from Keyboard - input() function, Python user input from the keyboard can be read using the input() built-in function. The prompt string is printed on the console and the control is given to the user to File "/Users/pankaj/Documents/PycharmProjects/PythonTutorialPro/ hello-world I have been working on Python for more than 5 years. Search in content. File Searching using Python There may be many instances when you want to search a system.Suppose while writing an mp3 player you may want to have all the ‘.mp3’ files present. Well here’s how to do it in a simple way.