0

photo This code can't load the log.txt file.
The file is in the temp folder.
Why can't I load it?
This code only displays the text: Search word: ABC.

text = input("Search word: ABC")
with open("C:\Temp\log.txt", encoding = "utf-8") as f:
    cnt = 0
    for line in f:
        l = line.strip().split()
        if (l[-1] == text):
            print(line.strip())
            cnt += 1
    if (cnt): print(cnt, "count")
    else: print(text, "No data.")
이현규
  • 3
  • 4
  • Please include any errors or return codes as it is very hard to understand what is failing without them – Woodz Jan 31 '20 at 03:28
  • There is no error. Just if I type ABC, This code need to find and print the ABC in txt, but it's not – 이현규 Jan 31 '20 at 03:59
  • Is there a return code or does the application hang? – Woodz Jan 31 '20 at 04:00
  • No hang. What does the return code mean? – 이현규 Jan 31 '20 at 04:05
  • It is the status when your Python application finishes running (see https://stackoverflow.com/q/285289/323177 for more details). Can you share how you are running this program (e.g. the command line or IDE) and screenshots/text shown? – Woodz Jan 31 '20 at 04:29
  • Added picture to content. If press Run, it is still running without shutting down. – 이현규 Jan 31 '20 at 04:42

2 Answers2

0

It seems like you need to type the word after running the program. The "ABC" you see is the prompt from the script i.e. it is not entered by you. That's why the program keeps running, waiting for the input and doesn't go further.

Here's your code slightly modified to make it clear.

text = input("Search word: ")
with open("C:\Temp\log.txt", encoding="utf-8") as f:
    cnt = 0
    for line in f:
        if text in line:
            print(line.strip())
            cnt += 1
    if cnt:
        print(cnt, "count")
    else:
        print(text, "No data.")
Yasir Khan
  • 645
  • 4
  • 9
0

I guess you understand that your code:

  • ask the user to input some text
  • count the occurrences of that text in the file C:\Temp\log.txt, under the conditions:
    • the text does not contains space
    • the text is at the end of the line
    • the text may be followed by one or more spaces
    • the text must be preceded by one or more spaces
    • the file cannot have empty lines

Under those conditions, your code should behave nicely. I would recommend to change text = input("Search word: ABC") to text = input("Search word: ") to make it clear that the user need to input some text.

If you still have unexpected results, check if you don't have any character encoding issue (like a terminal default encoding not being utf-8)

maxhaz
  • 380
  • 1
  • 2
  • 8