# 檔案 Files 在python讀寫檔案,可以用 `open(檔案路經, 模式)` 其中 `'r'`代表 read,`w`代表 write。 ```python= # 開啟檔案 file = open('some_file.txt', 'r') # 關閉檔案 file.close() ``` 檔案可以用的方法有: `close()` `read()` `write()` `readline()` `readlines()` `writelines()` `tell()` `seek()` ## read() 未指定參數讀全部,否則讀特定字元數。 ```python= file = open('some_file.txt', 'r') # 改成 content = file.read(2) 就會只讀兩個字元 content = file.read() print(content) file.close() ``` ## write() ```python= # 如果此檔案不存在,則新建一個檔案 file = open('some_file.txt', 'w') file.write('Hello world!') file.close() ``` ## with() 每次開檔案要記得關閉檔案(`close()`)。 我們可以用 `with` 來自動關檔案。 ```python= with open('some_file.txt', 'r') as file: print(file.read()) ``` 當 `with` 區塊結束時,檔案也會關閉。 若要開啟多個檔案: ```python= with open('a.txt', 'r') as a, open('b.txt', 'w') as b: pass ``` ## readline() 還記得我們在 `print()` 的時候,如果用 `'\n'`代表換行。 在 Windows 中,換行是 `'\r\n'`。 `readline()`讀取到 `'\n'`或`'\r\n'`時,會判斷成一行。 ```python= file = open('some_file.txt', 'r') firstLine = file.readline() print(firstLine) file.close() ``` 在使用`read`或`readline`時,「游標」都會往下,舉例來說: ```python= file = open('some_file.txt', 'r') print(file.readline()) # 顯示第一行 print(file.readline()) # 顯示第二行 print(file.readline()) # 顯示第三行 print(file.read()) # 顯示第四行~全部 file.close() ``` 行間會間隔一行,為什麼? ## writelines() 把list寫進檔案(不會自動加換行)。 ```python= file = open('some_file.txt', 'w') to_write = ['Hello', 'world', '!'] file.writelines(to_write) file.close() # Helloworld! ``` ```python= file = open('some_file.txt', 'w') to_write = ['Hello\n', 'world\n', '!\n'] file.writelines(to_write) file.close() # Hello # world # ! ``` ## tell()、seek() 待補 ## Lab 參考收據、發票,建立出格式。並讓使用者根據情況結帳,然後獲得收據。 把收據用文字檔案輸出。