-1

I am trying to make this code so the user is asked what line to search, then they enter it, and then you display the line the user is wanting.

    import os

    f = open("input_file_lab_1.txt","r")
    allData = f.read()#3

    cleanedData = allData.split("\n")
    name = input("enter line to search\n").strip()
   
    n = 0
    while n == 0:
    for line in range(len(cleanedData)): 
        if name in cleanedData[line]: 
            print(name) 
            n = 1
        else:
            pass
    
    f.close()

Not sure if there is any easier way. i also keep on getting the error

  File "os1.py", line 7, in <module>

  name = input("enter line to search\n").strip()#5

AttributeError: 'int' object has no attribute 'strip'
Anurag Reddy
  • 1,159
  • 11
  • 19
nicole
  • 1
  • Are you sure you're using Python 3? – MattDMo Sep 14 '20 at 19:03
  • i just saw the first error i am using i wasn't running it as python3, but it still doesnt work – nicole Sep 14 '20 at 19:05
  • Are you still getting the same error using Python 3? – svorcan Sep 14 '20 at 19:06
  • Looking at the above, the code is not correctly indented. Please post the exact code you are running. – alani Sep 14 '20 at 19:07
  • No, it lets me put in the user input and i tried using the number 1, then it just outputted a bunch of 1's – nicole Sep 14 '20 at 19:09
  • @nicole Yes, that is to be expected. What did you want it to do? – alani Sep 14 '20 at 19:10
  • Maybe you wanted `print(cleanedData[line])` instead of `print(name)`. Separate from that, your `for` loop would be a lot cleaner if you iterated directly over `cleanedData` rather than over `range(len(cleanedData))`). You are not using the indexes for anything other than to extract the coresponding element. – alani Sep 14 '20 at 19:10
  • Does this answer your question? ['int' object has no attribute 'strip' error message](https://stackoverflow.com/questions/17191741/int-object-has-no-attribute-strip-error-message) – gre_gor Sep 15 '20 at 04:12

2 Answers2

2

You can use this snippet:

import os

with open("input.txt","r") as f:
    name = input("enter line to search\n").strip()
    for line in f:
        if name in line:
            print(line)
            break

edit: using with statement instead of f.open()/close() as @alec_djinn suggested

  • @nicole yw. FYI: if you want say 'thanks' you can accept the answer, do not write comment like "thank you". it's from stack overflow help center. Read more: https://stackoverflow.com/help/someone-answers – Mikhail Pashkov Sep 14 '20 at 19:40
  • 2
    I suggest using the `with statement` instead of `f.open()/close()`, it is the preferred way. – alec_djinn Sep 14 '20 at 19:42
0

You may want to try python's standard library

https://docs.python.org/3/library/linecache.html#module-linecache

import linecache
lineNumber = input("enter line to search\n").strip()
line = linecache.getline(fileName, lineNumber)
print(line)