在 Python 中,文件 I/O(Input/Output)指的是程序与外部文件进行交互,包括读取文件内容和向文件写入数据。Python 提供了丰富的文件操作功能,可以轻松地读取、写入和操作文件内容。以下是关于 Python 文件 I/O 的详细介绍,并附带多个案例说明:
### 打开文件
要对文件进行读写操作,首先需要使用内置函数 `open()` 打开文件。语法如下:
```python
file = open('file_path', 'mode')
```
- `file_path` 是文件路径,可以是相对路径或绝对路径。
- `mode` 是打开文件的模式,包括读取模式 `'r'`、写入模式 `'w'`、追加模式 `'a'` 等。
### 读取文件内容
使用 `read()` 方法可以读取整个文件的内容,或者使用 `readline()` 逐行读取文件内容。例如:
```python
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
```
### 写入文件
使用 `write()` 方法可以向文件中写入数据。如果文件不存在,则会创建该文件;如果文件已存在,则会覆盖原有内容。例如:
```python
file = open('output.txt', 'w')
file.write("Hello, World!")
file.close()
```
### 追加内容
使用写入模式 `'a'` 可以在文件末尾添加内容而不覆盖原有内容。例如:
```python
file = open('output.txt', 'a')
file.write("\nThis is a new line.")
file.close()
```
### with 语句
使用 `with` 语句可以确保文件在使用完毕后被正确关闭,无需手动调用 `close()` 方法。例如:
```python
with open('example.txt', 'r') as file:
content = file.read()
print(content)
```
### 逐行读取
通过循环逐行读取文件内容。例如:
```python
with open('example.txt', 'r') as file:
for line in file:
print(line.strip()) # 去除行尾换行符
```
### 处理 CSV 文件
可以使用 Python 的内置模块 `csv` 来处理 CSV 文件。例如:
```python
import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
```
### JSON 文件操作
Python 的内置模块 `json` 可以方便地读写 JSON 格式的文件。例如:
```python
import json
data = {'name': 'Alice', 'age': 30}
with open('data.json', 'w') as file:
json.dump(data, file)
with open('data.json', 'r') as file:
loaded_data = json.load(file)
print(loaded_data)
```
以上是关于 Python 文件 I/O 的详细介绍,并提供了多个案例说明。文件 I/O 是 Python 编程中常见且重要的操作,能够让程序与外部文件进行数据交互。希望以上介绍对您有所帮助。