# Python - open file(2) - Exercise ###### tags: `Python HomeWork` **例**:着ぐるみのバイトの求人には幾つの条件があります。特に着ぐるみ自体の大きさが決まっているので身長制限があります。とある会社の求人には、160センチ以下が好ましいと書いていて、もし153センチの杏奈が応募したら果たしてTrueなのかFalseなのか、プログラミングで出力してください。 ``` 杏奈の身長を表す変数を利用して比較してください annaHigh = 153 出力例: Ture ``` :::info code: ```python= annaHigh = 153 print( annaHigh <= 160 ) ``` 答え: ![](https://i.imgur.com/SM2qRLJ.png) ::: -------------------------------------------- ## 問1:一行一行 ファイル「game.txt」の内容を読み込み、何行目表示するかを自由に決められるようにするプログラムを作ってください。 ``` 以下はgame.txtファイルの内容 Game,Price BIOHAZARD Village,9990 Fatal Frame: Maiden of Black Water,6600 SILENT HILL 3,990 SIREN 2,9800 Kuon,6126 Corpse Party,1520 ``` ``` **入力1:** 何行目まで出力しますか:2 **出力1:** Game,Price BIOHAZARD Village,9990 **入力2:** 何行目まで出力しますか:5 **出力2:** Game,Price BIOHAZARD Village,9990 Fatal Frame: Maiden of Black Water,6600 SILENT HILL 3,990 SIREN 2,9800 ``` :::info code: ```python= file=open("game.txt","r") line = file.readline() N = int(input("何行目まで出力しますか:")) A = 0 while True: print(line) line = file.readline() file.close() ``` 結果: ::: ## 問2:一行一行 ファイル「score.txt」の内容を読み込み、総和を求める。 ``` 以下はscore.txtファイルの内容 80 90 70 55 12 84 00 48 32 84 20 99 end **出力:** 総和:674 ``` :::info code: ```python= file=open('score.txt') scoreList=[i.strip() for i in file] scoreList=[ int(i) for i in scoreList[:-1]] print(sum(scoreList)) ``` 結果: ::: ## 問3:読み込み出力 ファイル「game.txt」の内容を読み込み、出力例のように出力すること。 * gameとpriceの幅はそれぞれ40と10です。 ``` 以下はgame.txtファイルの内容 Game,Price BIOHAZARD Village,9990 Fatal Frame: Maiden of Black Water,6600 SILENT HILL 3,990 SIREN 2,9800 Kuon,6126 Corpse Party,1520 ``` 出力例: ![](https://i.imgur.com/FwmcFzw.png) :::info code: ```python= file=open("game.txt") print("-"*53) for lines in file: line=lines.split(",") gameName=line[0] price=line[1] print("|{:<40}|{:>10}|".format(gameName,price[:-1])) ``` 結果: ::: ## 問4:読み込み、ゲーム値段。 ファイル「game.txt」の内容を読み込み、一番高いゲームと一番安いゲームを出力してください。 ``` 以下はgame.txtファイルの内容 Game,Price BIOHAZARD Village,9990 Fatal Frame: Maiden of Black Water,6600 SILENT HILL 3,990 SIREN 2,9800 Kuon,6126 Corpse Party,1520 ``` 出力例: ``` The most expensive is BIOHAZARD Village The cheapest is SILENT HILL 3 ``` :::info code: ```python= file=open("monster.txt") file.readline() title=file.readline() contents=file.readlines() print(title.strip()) mun=0 for i in contents: print("{}.{]".format(num+1,i.strip())) num+=1 index=int(input("どれが見たい?")) print(contents) name,atk,defen=[],[],[] for i in contents: monData=i.split() print(monData) name.append(monDate[0]) atk.append(monData[1]) defen.append(mondata[2]) ``` 結果: ::: ## 問5:モンスター ファイル「monster.txt」の内容を読み込み、指定したモンスターの能力値を確認できるプログラムを作ってください。まず、入力例のように内容を表示し、次にモンスターを指定できるようにします。指定したら指定されたモンスターの能力値と能力の平均値を出力します。なお、平均値を出力の際に、小数点以下二桁で出力してください。 ``` 以下はmonster.txtファイルの内容 Monster Name atk def Alice 80 100 Arsene 150 70 Bobo 99 85 ``` ``` **入力:** Name atk def 1.Alice 80 100 2.Arsene 150 70 3.Bobo 99 85 どれが見たい?2 **出力:** Name:Arsene , Atk: 150 , Def: 70 ,Ave: 110.00 ``` :::info code: ```python= ``` :::