0

Is there an existing way to read any files with python already ignoring characters that are to the right of a comment character (for example, #)?

For example, consider the file

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

I'm looking for something that could already be called as

file.readcomlines()
#or
readcomlines(file)

and return

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

Is there such a thing in python or I'm going to have to program this function manually? Web search was of no help at all.

TomCho
  • 3,204
  • 6
  • 32
  • 83

2 Answers2

0

You can use the Built-in function str.partition(sep)

line = "0, 6, 7 # this is a comment"
left_part = line.partition("#")[0]
Quoting Eddie
  • 1,501
  • 1
  • 11
  • 14
0

You could write a function that does this

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

For example

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

This is, however, only a crude way to solve this and isn't particularly robust. The character # may show up in a number of other places other than just comments.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218