围绕阅读小文件的python风格问题

Kev*_*eil 3 python coding-style idioms

在命名文件中读取最pythonic的方法是什么,剥离为空的行,仅包含空格,或者将#作为第一个字符,然后处理剩余的行?假设它很容易适合记忆.

注意:这样做并不难 - 我要问的是最蟒蛇的方式.我一直在写很多Ruby和Java,但我已经失去了感觉.

这是一个稻草人:

file_lines = [line.strip() for line in open(config_file, 'r').readlines() if len(line.strip()) > 0]
for line in file_lines:
  if line[0] == '#':
    continue
  # Do whatever with line here.
Run Code Online (Sandbox Code Playgroud)

我对简洁感兴趣,但不是以难以阅读为代价.

小智 5

发电机非常适合这样的任务.它们是可读的,保持完美的关注点分离,并有效地记忆使用和时间.

def RemoveComments(lines):
    for line in lines:
        if not line.strip().startswith('#'):
            yield line

def RemoveBlankLines(lines):
    for line in lines:
        if line.strip():
            yield line
Run Code Online (Sandbox Code Playgroud)

现在将这些应用于您的文件:

filehandle = open('myfile', 'r')
for line in RemoveComments(RemoveBlankLines(filehandle)):
    Process(line)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,很明显两个生成器可以合并为一个,但我将它们分开来展示它们的可组合性.