⑴ 如何在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)
### 注意事项:
在文件操作中,请遵循以下规则:
### 其他模式:
额外的文件打开模式包括: