ファイルの読み込みと集計
csvを読み込んで、Worldwide Grossを集計します
marvel.csv
Year,Title,Production Studio,Worldwide Gross
2008,Iron Man,Marvel Studios,585174222
2008,The Incredible Hulk,Marvel Studios,264770996
2008,Punisher: War Zone,Marvel Studios,54700105
2009,X-Men Origins: Wolverine,20th Century Fox,373062864
2010,Iron Man 2,Marvel Studios,623933331
2011,Thor,Marvel Studios,449326618
2011,X-Men: First Class,20th Century Fox,352616690
read_csv.py
import sys,csv
if len(sys.argv)!=2:
sys.stderr.write("Usage: {} FILENAME\n".format(sys.argv[0]))
exit()
file=sys.argv[1]
fh=open(file,'rb')
lines = fh.readlines()[1:]
fh.close()
count=0
for line in lines:
line = line.rstrip("\n")
row = line.split(',')
print(row)
count += int(row[3])
print("Total:{}".format(count))
出力
~ python read_csv.py marvel.csv
['2008', 'Iron Man', 'Marvel Studios', '585174222']
['2008', 'The Incredible Hulk', 'Marvel Studios', '264770996']
['2008', 'Punisher: War Zone', 'Marvel Studios', '54700105']
['2009', 'X-Men Origins: Wolverine', '20th Century Fox', '373062864']
['2010', 'Iron Man 2', 'Marvel Studios', '623933331']
['2011', 'Thor', 'Marvel Studios', '449326618']
['2011', 'X-Men: First Class', '20th Century Fox', '352616690']
Total:2703584826
csvからDictionaryに変換
DictReaderクラスを使うと便利に変換できます
csv_to_dictionary.py
import sys,csv
if len(sys.argv)!=2:
sys.stderr.write("Usage: {} FILENAME\n".format(sys.argv[0]))
exit()
file=sys.argv[1]
count=0
with open(file) as fh:
rd = csv.DictReader(fh, delimiter=',')
for row in rd:
print(row)
出力
~ python csv_to_dictionary.py marvel.csv
{'Title': 'Iron Man', 'Production Studio': 'Marvel Studios', 'Worldwide Gross': '585174222', 'Year': '2008'}
{'Title': 'The Incredible Hulk', 'Production Studio': 'Marvel Studios', 'Worldwide Gross': '264770996', 'Year': '2008'}
{'Title': 'Punisher: War Zone', 'Production Studio': 'Marvel Studios', 'Worldwide Gross': '54700105', 'Year': '2008'}
{'Title': 'X-Men Origins: Wolverine', 'Production Studio': '20th Century Fox', 'Worldwide Gross': '373062864', 'Year': '2009'}
{'Title': 'Iron Man 2', 'Production Studio': 'Marvel Studios', 'Worldwide Gross': '623933331', 'Year': '2010'}
{'Title': 'Thor', 'Production Studio': 'Marvel Studios', 'Worldwide Gross': '449326618', 'Year': '2011'}
{'Title': 'X-Men: First Class', 'Production Studio': '20th Century Fox', 'Worldwide Gross': '352616690', 'Year': '2011'}