-6

I am reading a text file titled "sample.txt" with 2 columns of data as follows.

ID Type

1 A

2 B

3 A

4 C

5 A

Now,

1) I want to only return rows whose 'Type' column value is 'A' and

2) I want to only return rows whose 'Type' column value is not 'A'.

Can anyone help me understand how this can be done in python? Thanks.

user8929822
  • 273
  • 1
  • 3
  • 13
  • 2
    It seems you need [this](https://stackoverflow.com/q/17071871/2901002). – jezrael Jan 22 '18 at 07:45
  • thanks @jezrael for pointing me in the right direction. I was able to figure it out. – user8929822 Jan 22 '18 at 13:54
  • Possible duplicate of [Select rows from a DataFrame based on values in a column in pandas](https://stackoverflow.com/questions/17071871/select-rows-from-a-dataframe-based-on-values-in-a-column-in-pandas) –  Apr 26 '18 at 00:27

1 Answers1

0

You didn't try very hard or at least didn't provide your attempts at cracking this.

def filterFileLines(filterFunction):
    with open("sample.txt") as file:
        # discard_first_line
        file.readline()

        for line in file:
            id, type = line.strip().split(' ')
            if filterFunction(id, type):
                print (line, end='')
        print('')

def isTypeA(a, b):
    return b == 'A'

def isNotTypeA(a, b):
    return not isTypeA(a, b)

if __name__ == '__main__':
    print('Lines with type == "A"')
    filterFileLines(isTypeA)

    print('lines with type not "A"')
    filterFileLines(isNotTypeA)
clement
  • 21
  • 1
  • 5