简体   繁体   English

从文件中删除注释行

[英]Remove comment lines from a file

I'm making a file type to store information from my program. 我正在创建一种文件类型来存储程序中的信息。 The file type can include lines starting with #, like: 文件类型可以包含以#开头的行,例如:

# This is a comment.

As shown, the # in front of a line denotes a comment. 如图所示,行前面的#表示注释。 I've written a program in Python that can read these files: 我已经用Python编写了一个程序,可以读取以下文件:

fileData = []

file = open("Tutorial.rdsf", "r")

line = file.readline()

while line != "":
    fileData.append(line)
    line = file.readline()

for item in list(fileData):
   item.strip()

fileData = list(map(lambda s: s.strip(), fileData))

print(fileData)

As you can see, it takes the file, adds every line as an item in a list, and strips the items of \\n. 如您所见,它将获取文件,将每一行添加为列表中的项目,并去除\\ n的项目。 So far, so good. 到现在为止还挺好。

But often these files contain comments I've made, and such the program adds them to the list. 但是这些文件通常包含我所做的注释,因此该程序会将它们添加到列表中。

Is there a way to delete all items in the list starting with #? 有没有一种方法可以删除列表中以#开头的所有项目?

Edit: To make things a bit clearer: Comments won't be like this: 编辑:让事情变得更清晰:注释不会像这样:

Some code:
{Some Code}    #Foo

They'll be like this: 他们会像这样:

#Foo
Some code:
{Some Code}

You can process lines directly in a for loop: 您可以直接在for循环中处理行:

with open("Tutorial.rdsf", "r") as file:
    for line in file:
        if line.startswith('#'):
            continue  # skip comments
        line = line.strip()

        # do more things with this line

Only put them into a list if you need random access (eg you need to access lines at specific indices). 仅在需要随机访问(例如,需要访问特定索引的行)时才将它们放入列表。

I used a with statement to manage the open file, when Python reaches the end of the with block the file is automatically closed for you. 我使用了with语句来管理打开的文件,当Python到达with块的末尾时,该文件将自动为您关闭。

It's easy to check for leading # signs. 检查前导#符号很容易。

Change this: 更改此:

while line != "":
    fileData.append(line)
    line = file.readline()

to this: 对此:

while line != "":
    if not line.startswith("#"):
        fileData.append(line)
    line = file.readline()

But your program is a bit complicated for what it does. 但是您的程序执行起来有些复杂。 Look in the documentation where it explains about for line in file: . 请参阅说明文件中有关for line in file:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM