简体   繁体   中英

Python:Printing rows only if a part of the row meets conditions

Apologies if this is a very basic question. I'm new to python and am attempting to get python to read a .txt file and print lines only if conditions are met. Below is a (very tiny) sample of my data:

在此处输入图片说明

I have done this before for one condition and it worked using the code:

file=open("sample.txt")

for row in file:
    if not "1e-22" in row:
        continue
    else:
        print row

However, I also need to also filter out the data based on columns 3 and 4 and I have tried multiple ways to do this with a variety of syntax errors. I've tried a multiude of different ways to no avail. My most recent attempt is below:

file=open("sample.txt")
for row in file:
    if file[4] is not "80":
        continue
    else:
        print row

This brings up the following error:

Traceback (most recent call last):
  File "test1.py", line 3, in <module>
    if file[0:4] is not "80":
TypeError: 'file' object has no attribute '__getitem__'

I've also tried converting the input into int, which would be earier to work with and I get the below error:

Traceback (most recent call last):
  File "test1.py", line 3, in <module>
    file=int(file)

    TypeError: int() argument must be a string or a number, not 'file'

I've tried so many different ways I think I'm missing something fundamental and would be very grateful for your help.

try following:

file=open("sample.txt")
for row in file:
    if row[4] is not "80":
        continue
    else:
        print row

It should be row and not file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM