# Python - open file(1) - 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: 以下は会社名のテキストファイルです。ユーザーがファイル名を入力し、ファイルの内容を印刷するためのプログラムを作成してください。 Company.txt ``` Craft Egg BANDAI Cygames SquareEnix KONAMI ``` ``` **入力例:** Please enter the file name:Company.txt **出力例:** Craft Egg BANDAI Cygames SquareEnix KONAMI ``` :::info code: ```python= fileName=input("Please enter the file name") file=open(fileName,"r") print(file.read()) file.close ``` 結果: ::: ## 問2: 「read.txt」ファイルの内容(内容はスペースで区切られている数字)を読み込み、それらの合計を計算し出力するプログラムを作成せよ。読み込み終了したらファイルを閉じること。 read.txt ``` 11 22 33 22 33 44 33 44 55 44 55 66 55 66 77 ``` ``` **出力例:** 660 ``` :::info code: ```python= file=open("read.txt","r") contens=file.read() file.close() contentlist=contents.split() print(contentlist) contentslist=[int(i) for i in contentlist] print(sum(contentlist)) ``` 結果: ::: ## 問3: 文字列「s」を入力させ、ファイル「read.txt」の内容を表示する。その後ファイルの内容から、文字列「s」を含む文字を削除すること。 そして指定した文字列を削除したファイル内容の表示。 read.txt ``` Apple Kiwi Banana Tomato Pear Durian ``` ``` **入力出力例:** === Before the deletion === ['Apple', 'Kiwi', 'Banana', 'Tomato', 'Pear', 'Durian'] Please enter the text you want to delete: Tomato === After the deletion === ['Apple', 'Kiwi', 'Banana', 'Pear', 'Durian'] ``` :::info code: ```python= file=open("read.txt","r") contents=file.read() file.close() contentlist=contents.split() print("=== Before the deletion ===") print(contentlist) deletString=input("Please enter the text you want to delete") contentlist.remove(deletString) print("=== After the deletion ===") print(contentlist) ``` 結果: ::: ## 問4: read.txtファイルを読み込み、ユーザに文字列s1と文字列s2を入力させ、ファイル内の文字列s1をs2に置き換え、元のファイルの内容と置換したファイルの内容を出力するプログラムを作成してください。 read.txt 以下がファイル内容: ``` watch shoes skirt pen trunks pants ``` ``` 入出力例: please enter s1:pen please enter s2:senakers === Before the replacement watch shoes skirt pen trunks pants === After the replacement watch shoes skirt senakers trunks pants ``` :::info code: ```python= ``` 結果: :::