简体   繁体   中英

Loading Specific Data from a CSV file python

I am dealing with CSV files that contains lots of data. Each row contains data in the format as shown below.

Name, Age, Sex, Birth Year

Mark, 18, M, 1978

Mary, 18, M, 1980

Marcus, 18, M, 1978

This data is repeated so on and so forth for apprixmately 200 lines. What I want to know is there a way that I can open this folder and read it but only print the lines that contain 1978. I,e for above data it would only print the Mark and Marcus lines.

Here is my code so far. How can I edit it to achieve my aim. Is it possible?

 f=open("Names.csv",'rU')
    lines = f.readlines()
    f.close()
    for line in lines:
        [x for x in lines if '1978' print x]
with open("Names.csv") as fh:
    for line in fh:
        if '1978' in line:
            print line

Note that there is a standard library module to deal with CSV files, but for your purposes you don't seem to need any of that; the above code snippet should do. However, if your needs become more complex you might do yourself a favor by reading CSV as CSV rather than as plain text.

Assign result of list comprehension.

with open('Names.csv') as f:
    lines = [line for lin in f if '1978' in line]

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