简体   繁体   中英

Printing .csv files in Python depending on the year?

I have a CSV file.

Each line contains data separated A Comma; each row is ended by a new line character. So in my file, the first data entry of each line is a year and the second entry in the line is the title of a film.

For example:

1990, Tie Me Up! Tie Me Down!

So, it just has a bunch of years, and then movie titles. My question is, how do I print the movie title IF it was made before 1990? So something like:

2015, Spongebob movie

wouldn't print.

So far I have:

f = open("filmdata.csv","r",encoding="utf-8")
for line in f:
    entries = line.split(",")
    if entries in f < 1990 :
        print(line)
f.close()

But nothing is printing out? But it doesn't say error or anything.. I'm trying to keep it in this format.

Although the previous answers will work in your generic case, it is a much better idea to use Python's csv module when working with a CSV. It is more extensible, provides handling of more complicated cases (like escaping quotes and data with commas), and is very easy to use.

The following code snippet should work in your case:

import csv

with open('filmdata.csv', 'r') as csvfile:
    data = csv.reader(csvfile, delimiter=',', encoding='utf-8')
    for year, movie in data:
        if int(year) < 1990:
            print (year, movie)

You can of course modify the print to use any format. If you want to separate by commas, this will work:

print('{}, {}'.format(year, movie))

Try this:

f = open("filmdata.csv","r",encoding="utf-8")
for line in f:
    entries = line.split(",")
    if int(entries[0]) < 1990 :
        print(line)
f.close()

Have you tried looking into using Pandas. I moc'd up a movie.csv file with 2 colums (year,title).

import pandas as pd
movies = pd.read_csv('movie.csv',sep=',',names=["year","title"])

Output of movies array:

    year    title
0   1990    Movie1
1   1991    Movie2
2   1992    Movie3
3   1993    Movie4
4   1994    Movie5
5   1995    Movie6
6   1996    Movie7
7   1997    Movie8
8   1999    Movie9
9   2000    Movie10

Let's say we'd like to see all the movies where the year is over 1994:

movies[movies['year']> 1994]

   year    title
5  1995   Movie6
6  1996   Movie7
7  1997   Movie8
8  1999   Movie9
9  2000  Movie10

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