2012-11-26 76 views
0

如果我有这样一个文本文件:如何使用while循环遍历文本文件?

 StudentA: 
     10 
     20 
     30 
     40 

     StudentB: 
     60 
     70 
     80 
     90 

我想打一个函数:

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

当我打电话吧,

 read_file(file,StudentA) 

,它会显示在列表中,如:

[10,20,30,40] 

我怎样才能做到这一点while循环?

+2

为什么你需要用'while'循环专门做? – jdotjdot

回答

2

我不确定你为什么要阅读使用while,for-loop会做得很好。但是,这是一种阅读文件的pythonic方式。

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

with语句处理地打开和关闭该文件,包括:如果一个异常被在内部块中引发。 for line in f将文件对象f视为一个迭代器,它会自动使用缓冲IO和内存管理,因此您不必担心大文件。

+0

在这种情况下,while循环有一定意义。 OP只想读取文件的一部分。而不是在'for'循环中插入'break',你可以用while循环来实现。 (虽然这两种方法都有点混乱) – mgilson

+1

如果您只想读取文件的一部分,那么您需要使用“break”的方式。有没有摆脱这一点。但是大多数人在尝试读取文件时会错过什么 - 该文件不存在?这个文件的大小是1GB?当一个人在单元测试阶段时,这些问题不会发生,但是当代码发布到野外,谁知道会发生什么。 –

0

请记住,StackOverflow不是一个代码写入服务。通常情况下,在你写出自己的答案之前,我不会做这样的事情,但有人今天帮了我一个忙,并且本着这种精神传递了善意。

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