简体   繁体   中英

How to read a file line by line, then print the line if it contains a string with a range of value in Python?

I'm a newbie with Python 2.7 and I'm still trying to get the hang of it.

I have a text file with a row of lines that contain strings like this:

"AA,,BB,2014-02-06,0,0|CC,,DD,2014-02-27,0,0|EE,,FF,2014-02-04,1,1"#"GG"#"USD"#"true"#Total : USD#1638.93#

(There's a bunch of text before 'USD' that varies with each line.)

I tried doing this:

with open('out_put_usjfk50.csv', 'rb') as f:
    reader = csv.reader(f, delimiter='#')
    for row in reader:
        amount = float(row[5])
        if amount <= 800:
            print row
        elif amount is None:
            pass

but I got the same error: ValueError: could not convert string to float:

I'm stumped. How do I go through each line to check for the integer value (that's part of a string), and then print the line(s) if it's less than, say, USD1500? I'd appreciate it if someone can point me to the right direction!

You have a CSV file; use the csv module :

import csv

with open('filename.csv', 'rb') as f:
    reader = csv.reader(f, delimiter='#')
    for row in reader:

New each row object is a list of strings; each string representing a column in your file.

Say the '1638.93' column is column 8, then you'd use (with Python using 0-based indexing):

amount = float(row[7])

Now you have a floating point number from that string, and you can test against it:

with open('filename.csv', 'rb') as f:
    reader = csv.reader(f, delimiter='#')
    for row in reader:
        amount = float(row[7])
        if amount <= 1500:
            print row

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