⑴ 如何在python程序中讀取和寫入文件
在Python中,讀取和寫入文件主要依賴於內置的`open()`函數及其相關方法。以下是一些基本示例,用於演示如何在Python程序中進行文件操作。
### 1. 打開文件以進行讀取
#### a) 讀取整個文件內容到字元串:
python
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
#### b) 逐行讀取文件:
python
with open('example.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line.strip())
### 2. 寫入文件
#### a) 覆蓋文件內容:
python
content_to_write = "Hello, World! This is a test."
with open('output.txt', 'w', encoding='utf-8') as file:
file.write(content_to_write)
#### b) 追加內容到文件末尾:
python
additional_text = "Appending some more text... "
with open('output.txt', 'a', encoding='utf-8') as file:
file.write(additional_text)
### 注意事項:
在文件操作中,請遵循以下規則:
### 其他模式:
額外的文件打開模式包括: