0

I am trying to read data in from a file in python and compare it to see if it matches some of the information. I have this

with open("data.dat", "r") as f: #read data in from the file
    for line in f:
        if line is "Static": #this adds the data for the static attack

When I read the data in from my file, it skips right over it. I am at a loss why.

Here is my data.dat file.

Static
0 10
1 50

2 Answers 2

3

You may use == to compare two strings:

with open("data.dat", "r") as f:
    for line in f:
        if line == "Static":

is is used to test two objects whether they are the same object (compare identity).

== is used to compare two variables' value.

Python Language Reference - Objects, values and types:

Every object has an identity, a type and a value. An object's identity never changes once it has been created; you may think of it as the object's address in memory. The is operator compares the identity of two objects; the id() function returns an integer representing its identity.

Sign up to request clarification or add additional context in comments.

Comments

0

For this application, you can use the in operator, like so:

with open("data.dat", "r") as f:
    for line in f:
        if "Static" in line:
            # do something

This is if you want any line with the substring "Static" to be caught by the condition, regardless of whether or not it is the only string in the line.

If you strictly want to catch lines that only have the substring "Static" in it, with the exception of trailing whitespaces, then you can use the == operator, like so:

with open("data.dat", "r") as f:
    for line in f:
        if line.strip() == "Static":
            # do something

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.