在Python中,读取和写入文件主要依赖于内置的`open()`函数及其相关方法。以下是一些基本示例,用于演示如何在Python程序中进行文件操作。1. 打开文件以进行读取 a) 读取整个文件内容到字符串:python with open('example.txt', 'r', encoding='utf-8') as file:content = file.read()print(content)...
如何在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)
### 注意事项:
在文件操作中,请遵循以下规则:
`'r'` 模式用于读取文件(Read)。`'w'` 模式用于创建或清空文件内容(Write)。`'a'` 模式在文件末尾追加内容(Append)。`encoding='utf-8'` 参数确保正确处理文本文件的编码。`with`语句确保文件在使用后自动关闭,避免资源泄露。 ### 其他模式:
额外的文件打开模式包括:
`'x'` 创建新文件,存在时引发错误。`'b'` 表示二进制模式,通常用于非文本文件。`'t'` 默认为文本模式,可以省略。`'+'` 允许读写操作。2024-09-08