在Python中,读写文件可以通过以下步骤进行:
打开文件
使用内置的`open()`函数来打开文件。该函数接受两个参数:文件名和打开模式。
打开模式可以是以下几种:
`'r'`:只读模式,只能读取文件内容,不能修改。
`'w'`:写入模式,只能写入文件内容,会覆盖原有内容。
`'a'`:追加模式,可以在文件末尾添加内容。
`'r+'`:读写模式,可以读取和写入文件。
`'b'`:二进制模式,用于处理二进制文件。
读取文件
一次性读取整个文件:
```python
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
```
逐行读取文件:
```python
with open('example.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line.strip()) strip()方法用于去除行尾的换行符
```
读取特定行:
```python
line_number = 2
with open('example.txt', 'r', encoding='utf-8') as file:
for i, line in enumerate(file):
if i == line_number - 1:
print(line.strip())
break
```
写入文件
写入单个字符串:
```python
with open('output.txt', 'w', encoding='utf-8') as file:
file.write('Hello, World!\n')
file.write('这是第二行内容。\n')
```
写入列表或数组:
```python
lines = ['Hello, Python!', 'Welcome to Python!']
with open('output.txt', 'w', encoding='utf-8') as file:
for line in lines:
file.write(line + '\n')
```
建议
使用`with`语句可以自动管理文件的打开和关闭,避免忘记关闭文件对象,从而减少资源泄漏的风险。
读取大文件时,建议逐行读取,以减少内存占用。
写入文件时,注意不同模式会带来的影响,例如`w`模式会覆盖原有内容,而`a`模式会在文件末尾追加内容。