Skip to main content
 首页 » 编程设计

Python:跳过打开文件的注释行并用当前行传递文件对象的函数

2024年10月25日10lonelyxmas

我正在尝试编写一些 Python 代码来为特定软件编辑一些(现有的)输入和输出文件。我感兴趣的所有文件都可能以第一个字符为 # 的注释行开头(注释行数未知)。

我总是想跳过那些注释行来阅读/存储重要的文本。因此,我想创建一个函数,对于以读取模式打开的文件对象,它将跳过注释行,以便下一次从文件对象读取的调用位于文件。目前我正在尝试创建一个类,然后使用 skip_comments() 方法(参见下面的代码):

import os 
class FileOperations: 
 
    def __init__(self, directory, filename): 
        self.directory = directory 
        self.filename = filename 
        self.filepath = os.path.abspath(os.path.join(directory,filename)) 
        self.fo = open(self.filepath,'r') 
 
    def skip_comments(self): 
        """ Passes the current position to the location of the first non-comment  
        line of self.fo""" 
 
        for line in self.fo: 
            if not line.lstrip().startswith('#'): 
                break 
        print line ## Just to check if in correct spot 

实例化一个类对象是可行的,我可以执行正常的对象文件操作,如 read() 和 seek():

In [47]: fh = FileOperations('file_directory','file.txt')` 
In [48]: fh.fo.read(10) 
Out[48]: '#This file'` 
In [49]: fh.fo.seek(0) 

但是当我尝试使用 skip_comments() 方法然后从目标文件中读取时,我遇到了问题:

In [50]: fh.skip_comments() 
20 740 AUX IFACE AUX QFACT AUX CELLGRP 
 
Out[50]: <open file '... file_dir\file.txt', mode 'r' at 0x0000000008797D20> 
In [51]: fh.fo.read(10) 
--------------------------------------------------------------------------- 
ValueError                                Traceback (most recent call last) 
<ipython-input-51-20f04ae797fe> in <module>() 
----> 1 fh.fo.read(10) 
 
ValueError: Mixing iteration and read methods would lose data  

有人可以帮我修复这个错误或建议更好的方法吗?谢谢!

请您参考如下方法:

您要做的是将 skip_lines() 函数变成生成器。下面的生成器根据您传递给它的文件名生成非注释行。

所以:

def skip_comments(filename): 
    with open(filename, 'rb') as f: 
        for line in f: 
            if not line.strip().startswith('#'): 
               yield line 
 
#then, to use the generator you've just created: 
for line in skip_comments(filename): 
    #do stuff with line 
 
#if you want all the lines at the same time... 
lines = list(skip_comments(filename)) 
#lines is now a list of all non-comment lines in the file 

编辑:更快(更密集)的版本是 skip_comments = lambda filename: (line for line in open(filename, 'rb') if not line.startswith('# '))。这使用了一个速度相当快的生成器表达式(在我的机器上节省了大约 1/3 的时间)。