0

if I have a text file like:

     StudentA:
      10
      20
      30
      40

      StudentB:
      60
      70 
      80
      90

I want to make a function :

    def read_file(file,student):
        file=file.open('file.txt','r')

when I call it,

     read_file(file,StudentA)

it will show the list like:

    [10,20,30,40]

How can I do it with a while loop?

1
  • 2
    Why do you need to do it specifically with a while loop? Commented Nov 26, 2012 at 6:32

2 Answers 2

2

I am not sure why you want to read using while, for-loop will do just fine. But here is a pythonic way to read files.

with open(...) as f:
    for line in f:
        <do something with line>

The with statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f treats the file object f as an iterable, which automatically uses buffered IO and memory management so you don't have to worry about large files.

Sign up to request clarification or add additional context in comments.

2 Comments

In this case, a while loop makes some sense. OP only wants to read part of the file. Rather than inserting a break into the for loop, you could do it with a while loop. (Although, both ways are a little messy)
well if you are trying to read only part of a file, either which way you use break needs to be used. there is no getting away from that. But what most people miss when trying to read files is - what is that file is not present? what is that file is 1GB in size? these problems dont occur when one is at unit testing phase but when the code goes to the wild who knows what to expect.
1
import re

def read_file(filename, student):
    with open(filename, 'r') as thefile:
        lines = [x.strip().upper() for x in thefile.readlines()]
    if student[-1] != ':':
        student += ':'
    current_line = lines.index(student.upper()) + 1
    output = []
    while current_line < len(lines) and re.search('^\d+$', lines[current_line]):
        output.append(int(lines[current_line]))
        current_line += 1
    return output
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.