python如何用csv模块删除csv文件中出现的空行
时间: 2024-02-02 08:04:08 浏览: 38
你可以使用 `csv` 模块和 `pandas` 库来删除 CSV 文件中的空行。下面是使用 `csv` 模块实现的方法:
```python
import csv
# 读取 CSV 文件
with open('example.csv', 'r') as file:
reader = csv.reader(file)
# 过滤空行并写入新的 CSV 文件
with open('new_example.csv', 'w', newline='') as new_file:
writer = csv.writer(new_file)
for row in reader:
if any(field.strip() for field in row):
writer.writerow(row)
```
这段代码会读取 `example.csv` 文件中的所有行,过滤掉空行,然后将有效行写入到 `new_example.csv` 文件中。注意,我们在 `open()` 函数中加入了参数 `newline=''`,这样可以避免写入 CSV 文件时出现空行。
如果你想使用 `pandas` 实现同样的功能,可以使用下面的代码:
```python
import pandas as pd
# 读取 CSV 文件
df = pd.read_csv('example.csv', skip_blank_lines=True)
# 将有效行写入到新的 CSV 文件中
df.to_csv('new_example.csv', index=False)
```
这段代码会读取 `example.csv` 文件中的所有行,过滤掉空行,然后将有效行写入到 `new_example.csv` 文件中。注意,我们在 `read_csv()` 函数中加入了参数 `skip_blank_lines=True`,这样可以避免读取 CSV 文件时出现空行。