Liquidity
Liquidity

Reputation: 625

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.

Upvotes: 1

Views: 4169

Answers (3)

Yaman Jain
Yaman Jain

Reputation: 1245

That's an if condition that expects predicate statement not the assignment.

if line.startswith('#'):

startswith(...) S.startswith(prefix[, start[, end]]) -> bool

Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.

Upvotes: 0

Taku
Taku

Reputation: 33764

Although you're relatively new, you should start learning to use list comprehension, here is an example on how you can use it for your situation. I explained the details in the comments and the comments are matched to the corresponding order.

splitdata = [line.split() for line in file if line.startswith('#')]
# defines splitdata as a list because comprehension is wrapped in []
                          # make a for loop to iterate through file
                                           #checks if the line "startswith" a '#'
                                           # note: you should call functions/methods using the () not []
             # split the line at spaces if the if startment returns True

Upvotes: 1

Surajano
Surajano

Reputation: 2688

Correct the if statement and the indentation,

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

Upvotes: 4

Related Questions