readlines readline

Asked 2 years ago, Updated 2 years ago, 82 views

Save it to a variable called code to open the file

''' def searching(name):

code.seek(0, 0)
lines = code.readlines()
for line in lines:
    item = line.split()
    if name in item:
        return line

print searching ('No. 4)

print searching ('No. 5)

code.close() '''

Q. Inside the open file, ~~~~~ Number four!

~~~~~~ Number 4~~~~

~~~~~~ Number 4~~~~

~~~~~~ Number 4~~~~

Number 5!

Number 5!

Number 5!

Number 5!

Number 6!

Number 6!

Number 6!

Number 6!

It's made up of this kind of form. I want to get the results of all the lines with #4 If you do it, only the first line that contains number 4 and the first line that contains number 5 will be returned.ㅠ<

I'd appreciate it if you could tell me what went wrong. (Crying)

python2.7 readline

2022-09-21 12:37

1 Answers

Your code tells you to look at each row sequentially and return only those rows if they contain '4'.

This means that all rows containing '4' are not output; only the first row is output.

To solve this problem, you should save the row containing '4' in the list and modify it to return it all at once at the end.

It will be easy to understand if you refer to the following code.

def searching(name):
    code.seek(0, 0)
    lines = code.readlines()

    result = [] # List of rows containing '4'
    for line in lines:
        item = line.split()
        if name in item:
            result.append(line) # Keep it in the list without returning it immediately

    return result #Return all at once

print searching ('4')
code.close()


2022-09-21 12:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.