-1

First timer here with really using files and I/O. I'm running my code through a tester and the tester calls the different files I'm working with through my code. So for this, I'm representing the file as "filename" below and the string I'm looking for in that file as "s". I'm pretty sure I'm going through the lines of the code and searching for the string correctly. This is what I have for that :

def locate(filename, s):

    file= open(filename)
    line= file.readlines()
    for s in line:
        if s in line:
            return [line.count]

I'm aware the return line isn't correct. How would I return the number of the line that the string I'm looking for is located on as a list?

0

3 Answers 3

2

You can use enumerate to keep track of the line number:

def locate(filename, s):
    with open(filename) as f:
        return [i for i, line in enumerate(f, 1) if s in line]

In case the searched string can be found from first and third line it will produce following output:

[1, 3]
Sign up to request clarification or add additional context in comments.

8 Comments

Did you mean to return [i]? I think you just want i?
Question states that return value should be a list: "return the number of the line that the string I'm looking for is located on as a list". Of course if integer is preferred then it should be i as you suggested.
Ah! I think it is item and index together.
Could be, difficult to tell since there's no example of preferred output. Line number & line contents would obviously be return [i, line].
Conclusion. Unclear :P
|
0

You can use enumerate.

Sample Text File

hello hey s hi
hola
s

Code

def locate(filename, letter_to_find):

    locations = []
    with open(filename, 'r') as f:
        for line_num, line in enumerate(f):
            for word in line.split(' '):
                if letter_to_find in word:
                    locations.append(line_num)
    return locations

Output

[0, 2]

As we can see it shows that the string s on lines 0 and 2.
Note computers start counting at 0

Whats going on

  1. Opens the file with read permissions.

  2. Iterates over each line, enumerateing them as it goes, and keeping track of the line number in line_num.

  3. Iterates over each word in the line.

  4. If the letter_to_find that you passed into the function is in word, it appends the line_num to locations.

  5. return locations

Comments

0

These are the problem lines

for s in line:
    if s in line:

you have to read line into another variable apart from s

def locate(filename, s):

    file= open(filename)
    line= file.readlines()
    index = 0;
    for l in line:
        print l;
        index = index + 1
        if s in l:
            return index


print locate("/Temp/s.txt","s")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.