Reading a specific line from a text file

Hi i’m new here and new to python…

i want to write a code in python 2.7 to be able to read a text file and search for a specific sentence,
if it finds that sentence it should print a message in large letters in the middle of the screen,
if not it should print another message and then i want to make it be stand alone (i mean
windows executable file).

I know it is pretty easy what i ask…but i’m too new to complete it relatively soon. I’m choosing
python 2.7 because newer versions are slightly different and it might be confusing for me
to understand every line of the code.

thanks anyone willing to help :slight_smile:

It definitely won’t be more confusing, and there are lots of people here happy to help with specific questions! But regardless, Python 2.7 was End-of-Lifed over two years ago. No new code should ever use Python 2.7 and it’s not a good choice to start learning Python with in 2022, either.

hi
it’s what i’ve started to learn from school long ago…so that’s
why i prefer 2.7 so i can easily understand most of the code.

but ok if somebody can help with the code on a newer version

no problems :slight_smile:

The newer version has been out for more the 10 years!

Assume you have written wanted, foundand display functions and NOHIT message. Something like:

with open(filename) as f:
    for line in f:
        if wanted(line):
            msg = found(line)
            break  # stop after first hit?
    else:  # no hits
        msg = NOHIT
display(msg)

Making standalone executables has been discussed on python-list and very likely on stackoverflow.com.

1 Like

Ok thank you for the part of the code that need, but i can’t do the remaining…
about functions i remember i should type something like the following:

def wanted():
def found():
def display():

hmm…let’s make it more simple… :slightly_smiling_face:
i need my code to open a text file search for a specific sentence in the text file
and then make a beep sound if that sentence cannot be found.

is that easier to be done?

Nobody can help me with the code posted by Terry Jan Reedy?

We assume that you are learning python and do not want to cheat you of the experience in solving the problem yourself. That experience will take you far.

What can we do to unblock you?

Do you understand the algorithm that Terry is using?

Have you tried to write any of the three function that Terry outlined you need?
Please share that code.

wanted= 123456789
 
def display():
     print ('The specific text exists in line: '), line

that’s how far i guess i can do…but as i said in my last post let’s make it more simple
no messages…just a beep from the pc speaker in case the line is not found…

Terry shows that wanted is a function, notice the use if ().

def wanted(a_line):
      # your code that examines a_line and return True if you want the line
      # otherwise return False.

Terry shows the display function is called with one argument:

def display(message):
      # your code here that does something with message
1 Like
text= 123456789
filename= "text.txt"

with open(filename) as f:
    wanted(text)

def wanted(a_line):
   for line in f:
        if wanted(line):
            msg = found(line)
            break  # stop after first hit?
        else:  # no hits
             msg = NOHIT

i did my try to continue the code and i think it runs…i’ve tested it online and i got this error:

Traceback (most recent call last):
File “”, line 4, in
FileNotFoundError: [Errno 2] No such file or directory: ‘text.txt’

so i guess up to here it’s alrighr since it searches for the file, right?.. what’s next?? :grinning:

Run the code on your computer so that you make a test.txt to try it with.

Do you have python installed? If on Windows then you use the py.exe program to run your code:

py mycode.py

i couldn’t install python beyond version 3 so i installed the closest working version
so the code had some more errors and changed it to this:

text= 123456789
filename= "text.txt"

def wanted(a_line):
   for line in f:
        if wanted(line):
            msg = found(line)
            break  # stop after first hit?
        else:  # no hits
             print (line)

with open(filename) as f:
    wanted(text)

it can open the file and print on the screen every line in it…but it’s just that…
now what else it needs so it can search for the specific line and if not found
to make a beep from the pc speaker? i don’t know how to modify it more.

any reply??

That code does not run.

Can you post a version of your code that you have tested runs please?

Hi, i does run, it opens the file and prints the contents from the last to the first
but i don’t know what to do next so it can find if the “text= 123456789” exists
and if not to make a sound from the pc speaker.

It does not. found is not defined anywhere, resulting in NameError.

This is because wanted calls itself recursively until all lines from the input file have been consumed. At that point the stack begins to pop, with each frame returning None. Since None is falsey, the else clause runs, which prints the line which was used to call wanted in that frame. Since the stack pops from top to bottom, the lines are printed in reverse order.

If the file is long enough, you will get a RecursionError instead.

To check if a string contains a substring, use in:

if str(text) in line:
    break

Use a for-else loop:

for line in f:
    if str(text) in line:
        break
else:  # This only runs if the for loop is not exited via break.
    print("\a")

"\a" is the bell character. Printing it may cause the computer to

  • beep
  • vibrate
  • blink
  • do something else
  • all of the above
  • none of the above

depending on system configuration.

Sorry it does run. I missed that f is a global variable.

It runs by accident not by design.

ok i’ll try to put things together and if i find any difficulty
i’ll say…