python-使用注释语法读取文件

python-使用注释语法读取文件,python,file,Python,File,有没有一种现有的方法可以读取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已经忽略注释字符右侧的字符的文件(例如,
#

例如,考虑文件

 # 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中是否有这样的东西,或者我必须手动编写这个函数?网络搜索毫无帮助。

您可以使用内置功能


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

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 ']

然而,这只是解决这一问题的一种粗略方法,并不特别可靠。字符
#
可能会出现在除注释之外的许多其他位置。

因此您的答案是“否”,默认情况下不会出现这种情况。我必须自己用这个来编程。我说的对吗?这个解决方案不是基于字符串的散列,而不是注释吗?@alexwlchan:是的,是这样的。但在这个场景中,似乎只有整数列表类型的部分位于散列的左侧。
>>> readcomlines('test.txt')
['', '0, 6, 7 ', '5, 6, 7 ', '7, 6 ']