Search code examples
pythonstartswith

Python: Extract single line from file


Very new, please be nice and explain slowly and clearly. Thanks :)

I've tried searching how to extract a single line in python, but all the responses seem much more complicated (and confusing) than what I'm looking for. I have a file, it has a lot of lines, I want to pull out just the line that starts with #.

My file.txt:

"##STUFF"                                                                                                       
"##STUFF"                                                                                                       
#DATA 01 02 03 04 05
More lines here
More lines here
More lines here

My attempt at a script:

file = open("file.txt", "r")

splitdata = []

for line in file:
    if line.startswith['#'] = data
    splitdata = data.split()
    print splitdata

#expected output:
#splitdata = [#DATA, 1, 2, 3, 4, 5]

The error I get:

line.startswith['#'] = data

TypeError: 'builtin_function_or_method' object does not support item assignment

That seems to mean it doesn't like my "= data", but I'm not sure how to tell it that I want to take the line that starts with # and save it separately.


Solution

  • Correct the if statement and the indentation,

    for line in file:
        if line.startswith('#'):
            print line