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.

0

2 Answers 2

0

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

line = "0, 6, 7 # this is a comment"
left_part = line.partition("#")[0]
Sign up to request clarification or add additional context in comments.

3 Comments

So your answer is no, there isn't this by default. I have to program it myself using this. Am I right?
Won't this solution split on hashes that are part of strings, not comments?
@alexwlchan: Yes, it would. But it seems that in this scenario there are only integer-list-type parts on the left-hand side of the hash.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.