Use Python to select rows with a particular range of values in one column

前端 未结 3 940
执笔经年
执笔经年 2020-12-30 18:00

I know this is simple, but I\'m a new user to Python so I\'m having a bit of trouble here. I\'m using Python 3 by the way.

I have multiple files that look something

3条回答
  •  我在风中等你
    2020-12-30 18:13

    ITYM

    with open("addressbook1.txt", 'r') as f:
        # with automatically closes
        file_data = ((line, line.split("\t")) for line in f)
        with open("college_age.txt", 'w') as g, open("adult_age.txt", 'w') as h:
            for line, (name, date, age, sex, color) in file_data:
                if int(age) < 23: # float() if it is not an integer...
                    g.write(line)
                else:
                    h.write(line)
    

    It might look like the file data is iterated through several times. But thanks to the generator expression, file data is just a generator handing out the next line of the file if asked to do so. And it is asked to do so in the for loop. That means, every item retrieved by the for loop comes from the generator file_data where on request each file line gets transformed into a tuple holding the complete line (for copying) as well as its components (for testing).

    An alternative could be

    file_data = ((line, line.split("\t")) for line in iter(f.readline, ''))
    
    • it is closer to readlines() than iterating over the file. As readline() acts behind the scenes slightly different from iteration over the file, it might be necessary to do so.

    (If you don't like functional programming, you as well could create a generator function manually calling readline() until an empty string is returned.

    And if you don't like nested generators at all, you can do

    with open("addressbook1.txt", 'r') as f, open("college_age.txt", 'w') as g, open("adult_age.txt", 'w') as h:
        for line in f:
            name, date, age, sex, color = line.split("\t")
            if int(age) < 23: # float() if it is not an integer...
                g.write(line)
            else:
                h.write(line)
    

    which does exactly the same.)

提交回复
热议问题