python读取带有注释语法的文件

2024-04-25 20:20:55 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种现有的方法可以读取python已经忽略注释字符右边的字符的文件(例如,#

例如,考虑文件

 # this is a comment
 0, 6, 7 # this is a comment
 5, 6, 7 # this is a comment
 7, 6 # this is a comment

我在找一个可以叫做

file.readcomlines()
#or
readcomlines(file)

然后回来

['0, 6, 7 ', '5, 6, 7 ', '7, 6 ']

python中有这样的东西吗?或者我必须手动编写这个函数?网络搜索毫无帮助


Tags: or文件方法函数网络iscomment手动
2条回答

您可以使用内置函数^{}

line = "0, 6, 7 # this is a comment"
left_part = line.partition("#")[0]

你可以写一个函数来实现这一点

def readcomlines(path):
    with open(path) as f:
        return [line.split('#', 1)[0] for line in f if '#' in line]

例如

>>> readcomlines('test.txt')
['', '0, 6, 7 ', '5, 6, 7 ', '7, 6 ']

然而,这只是解决这个问题的一种粗略方法,并不是特别有效。字符#可能出现在除注释以外的许多其他地方

相关问题 更多 >