# ファイル操作
###### tags: `Python`
## ファイル
ファイルとは、コンピュータに何らかのデータを長期間にわたって保存しておく際に使用されるものだ。
* テキストファイル
* アプリケーションソフトの実行ファイル
* 各種画像ファイル
* 音楽
* 音声を含んだファイル
* Pythonのスクリプト
## ファイル操作
1. モードを指定してファイルを開く
2. 必要に応じた処理
3. ファイルを閉じる
## オープン
ファイルを開いてファイルの中身にアクセスできる状態にする必要があります。ファイルをオープンするにはopen()を使います。
:::info
開檔
想對檔案進行操作,首先得先打開檔案,使檔案在一個能存取的狀態下。而如何開起檔案在python裡是使用open()。
:::
```
file object = open(file name, mode = 'r')
```
### オープンモード
| mode | 説明 |
| -------- | -------- |
| a | 追記モード。読み込んだファイルの最後に追記する。 |
| r | 読み込みモード。ファイルを読み込む際に使用する。モードを指定しない場合はデフォルトでrとなる |
| w | 書き込みモード。同名のファイルがある場合、上書きしてしまう。ファイルが存在しない場合に新規作成をする。 |
:::info
檔案開啟模式
| モード | 説明 |
| -------- | -------- |
| a | 追加模式。於開啟過後的檔案內容最尾端追加內容。 |
| r | 讀取模式,讀取檔案時使用。若不指定開啟模式則預設為r。 |
| w | 寫入模式。若存在同名檔案,則將其覆蓋;不存在則建立新檔。 |
:::
---
## open(file name, 'r')
ファイルを読み込む際に使用する。
:::info
只讀取檔案時使用。
:::
```python=
file = open('Company.txt', 'r')
```
## read()
ファイルからテキストを読み込む。
:::info
從檔案讀取text(本文)
:::
```python=
file.read()
```
## close()
closeメソッドでファイルを閉じる。
:::info
以close方法來關閉檔案
:::
```python=
file.close()
```
---
### 例
Company.txt
```
Google
Twitter
Amazon
Facebook
Yahoo
```
ファイルを利用する
:::info
利用檔案。
:::
```python=
file = open('Company.txt', 'r')
print(file.read())
file.close()
```
**Results:**
```
Google
Twitter
Amazon
Facebook
Yahoo
```
---
## with
自動で閉じるためにwithを利用します。
:::info
若要讓檔案自動關閉則使用with。
:::
```python=
with open('fruits.txt', 'r') as file:
print(file.read())
```
**Results:**
```
Google
Twitter
Amazon
Facebook
Yahoo
```
:::danger
很多時候為撰寫速度與方便的結果,我們經常會把檔案開啟之後,就忘記關閉它。小小程式也許並不會讓人在意,但是當我們正在開發大型應用程式時,這樣的壞習慣經常會帶來無法預期的結果。
因此在Python手冊中也提倡了clean-up的動作,簡單地講,就是必須考慮到某些程式行為如何善後。以開檔為例,善後的動作當然就是關檔。
file變數在離開, with 區塊後,都能夠被自動地結束,以達成 clean-up 的目的。
:::
---
## for line in file:
文字列を1行ずつ取得します。
:::info
取得每一行的字串。
:::
```python=
file = open('Company.txt', 'r')
for line in file:
print(line)
file.close()
```
**Results:**
```
Google
Twitter
Amazon
Facebook
Yahoo
```
## readline()
ファイルから1行ずつ読み出し、文字列を返すメソッドです。
```python=
file = open('Company.txt', 'r')
line = file.readline()
print(line)
file.close()
```
**Results:**
```
Google
```
読み込みを行うサイズも指定できますよ。
```python=
file = open('Company.txt', 'r')
line = file.readline(2)
print(line)
file.close()
```
**Results:**
```
Go
```
すべての内容を読み込むにはループ処理を使用します。
```python=
file = open('Company.txt', 'r')
line = file.readline()
while line: # lineが取得できる限り繰り返す
print(line)
line = file.readline()
file.close()
```
**Results:**
```
Google
Twitter
Amazon
Facebook
Yahoo
```
改行コードを削除します。
```python=
file = open('Company.txt', 'r')
line = file.readline()
while line: # lineが取得できる限り繰り返す
line = line.strip()
print(line)
line = file.readline()
file.close()
```
**Results:**
```
Yahoo
Google
Twitter
Amazon
Facebook
Yahoo
```
## readlines()
「readlinesメソッド」はファイル内容をすべて読み込み、各行を要素とするリストを返すメソッドです。readlineメソッドとは違い、反復処理を簡単に記述できますよ。
readlineメソッドと同じように、要素となる文字列の末尾には改行コードが含まれることに注意してください。
また、readメソッドと同じようにreadinesメソッドでは基本的にはすべての内容が一度に読み込まれる点には注意しておきましょう。
```python=
file = open('Company.txt', 'r')
lines = file.readlines()
print(lines)
file.close()
```
**Results:**
```
['Google\n', 'Twitter\n', 'Amazon\n', 'Facebook\n', 'Yahoo']
```
readlines( )で読み込んだファイルを1行ずつ表示するにはfor文を使用して次のように記述します。
```python=
file = open('Company.txt', 'r')
lines = file.readlines()
for i in lines:
print(i)
file.close()
```
**Results:**
```
Google
Twitter
Amazon
Facebook
Yahoo
```
## open(file name, 'w')
ファイルを書き込み際に使用します。
* ファイルが存在しなければ新規作成します。存在している場合は上書きとなってしまうので注意しましょう。
```python=
file = open('GameCompany.txt', 'w')
```
## write()
ファイルオブジェクトの`write()`メソッドを使うと文字列を書き込むことができる。
```python=
file = open('GameCompany.txt', 'w')
file.write('BANDAI')
file.close()
```
**Results:**

write()の引数には文字列のみ指定可能。それ以外の型だとエラー(TypeError)となる。
```python=
file = open('GameCompany.txt', 'w')
file.write(10)
file.close()
```
**Results:**

**修正**
```python=
file = open('GameCompany.txt', 'w')
# file.write(10)
file.write(str(10))
file.close()
```
**Results:**

### write() Example:
```python=
file = open('GameCompany.txt', 'w')
file.write('Craft Egg ')
file.write('BANDAI ')
file.write('Cygames ')
file.close()
```
**GameCompany.txt Results:**

### ファイルへの書き込みで改行
文字列の途中で改行したい場合は、 `\n`で改行できます。
```python=
file = open('GameCompany.txt', 'w')
file.write('Craft Egg \n')
file.write('BANDAI \n')
file.write('Cygames ')
file.close()
```
**GameCompany.txt Results:**

### writelines()
ファイルオブジェクトの`writelines()`メソッドを使うとリストを書き込むことができる。
```python=
game_company = ['Craft Egg ', 'BANDAI ', 'Cygames ']
file = open('GameCompany.txt', 'w')
file.writelines(game_company)
file.close()
```
**GameCompany.txt Results:**

### writelines(): 改行
```python=
game_company = ['Craft Egg \n', 'BANDAI \n', 'Cygames ']
file = open('GameCompany.txt', 'w')
file.writelines(game_company)
file.close()
```
**GameCompany.txt Results:**

## open(file name, 'a')
追記
* ファイルが存在しない場合は新規作成される。
```python=
file = open('GameCompany.txt', 'a')
file.write('\nSquareEnix')
file.close();
```
**GameCompany.txt Results:**

## os.path.isfile()
ファイルの有無を確認して処理を分ける
:::info
確認檔案是否存在,依其結果執行程式。
:::
```python=
import os #osモジュールをインポートする宣言
if os.path.isfile('GameCompany.txt', 'r'):
print('GameCompany.txt', 'があります')
else:
print('GameCompany.txt', 'はありませんでした')
if os.path.isfile('ABC.txt'):
print('ABC.txt', 'があります')
else:
print('ABC.txt', 'はありませんでした')
```
**Results:**
```
GameCompany.txt があります
ABC.txt はありませんでした
```
## 複数のファイルの読み込み

**GameCompany_1.txt**
```
Bethesda
Ubisoft
CD Projek
Naughty Dog
```
**GameCompany_2.txt**
```
Capcom
PlatinumGames
SquareEnix
```
### Example:
ファイル名がGameCompany_で始まるすべてのファイルコンテンツを読み取ります。
* glob: 特定のパターンにマッチするファイルを取得できるモジュール
* 「*」はワイルドカード文字と呼ばれるもので「任意の文字列」を表します。
```python=
import glob #globモジュールを宣言
print(glob.glob("GameCompany_*.txt"))
# ['GameCompany_1.txt', 'GameCompany_2.txt']
for file in glob.glob("GameCompany_*.txt"):
file = open(file, 'r')
print(file.read())
```
**Results:**
```
['GameCompany_1.txt', 'GameCompany_2.txt']
Bethesda
Ubisoft
CD Projek
Naughty Dog
Capcom
PlatinumGames
SquareEnix
```