--- title: Python Input & Output tags: python, io --- ## I/O ### Simple I/O - print(*\*objects, sep=' ', end='\n', file=sys.stdout, flush=False*) - 輸出資訊 - `*objects`: 你想要輸出的參數 - `sep`: 輸出自動產生的間隔 - `end`: 輸出預設的結尾 - `file`: 選擇輸出位置 ```python= print('Hello World') # Hello World print("I'm", 20, 'years old.') # I'm 20 years old. print(1, 2, 3, sep='+', end='=?') # 1+2+3=? with open('a.txt', 'w') as fd: print('Hello World', file=fd) ``` - input(*[prompt]*) - 取得輸入 - Return type is string ```python= msg = input() # You will see nothing in your windonw msg = input('Type something: ') # Using prompt n = int(input('Give me a number: ')) numbers = list(map(int, input('> ').split(' '))) ``` ### File I/O 1. 開啟檔案: 使用 open 內建函式 - [更詳細的參數用法](https://docs.python.org/3/library/functions.html?highlight=open#open) - 基本會用到的參數 - file - 必要 - 為一絕對、相對的檔案路徑 - 型別為字串 - mode - Default is `'r'` - 非必要,但一般都會填 - 開啟檔案的模式 - `'r'` : read only - `'r+'` : read and write, no Truncation - `'w'` : write only, Truncation - `'w+'` : read and write, Truncation - `'a'` : append, always append before EOF - `'b'` : binary - `'rb'`、`r+b` : no Truncation - `'wb'`、`'w+b'` : Truncation - 型別為字串 - encoding - 非必要,偶爾會需要用到 - 型別為字串 - 回傳一檔案物件,利用此物件進行File I/O > Truncation : 開啟檔案時會把原本檔案刪掉 2. 檔案物件(以下簡稱 f_obj) - 常用屬性 - `f_obj.closed` - Return Ture if f_obj is closed - `f_obj.name` - Return file name - `f_obj.mode` - Retrun file open mode - 常用函式 - `f_obj.close()` - 關閉檔案物件 - 當檔案物件的參考(變數)參考到其他檔案物件時,python會自動關閉檔案 - `f_obj.read([count])` - 讀取檔案內容 - count 為要讀取多少 bytes - 沒有指定參數,則會盡可能地讀全部的資料 - Return string - Return `''` if reached EOF - `f_obj.readline()` - 讀取一行資料包含`'\n'` - Return string - Return `''` if reached EOF - `f_obj.readlines()` - 讀取整個檔案,每一行(包含"\n")為每一個Element - Return **list** - 等同於 `f_obj.read().split('\n')` - 等同於 `list(f_obj)` - `f_obj.write(string or bytes)` - 將資料寫入檔案 - 寫入的資料不是string就是bytes(看模式) - Return bytes which are written successfully ```python= # 分享一個曾經看過的寫法 f_obj = open('example.txt', 'r') # line包含"\n" for line in f_obj: print(line, end) f_obj.close() ``` 這樣的好處我想應該是可以節省資料的儲存空間