python保存csv指定列的数据
时间: 2024-02-17 11:20:13 浏览: 60
要保存 CSV 文件中指定列的数据,你可以使用 Python 的 `csv` 模块来处理。下面是一个示例代码:
```python
import csv
def save_selected_columns(input_file, output_file, selected_columns):
with open(input_file, 'r', newline='') as file:
reader = csv.reader(file)
headers = next(reader) # 读取文件的第一行作为表头
# 确定所选列的索引
selected_indexes = [headers.index(col) for col in selected_columns]
with open(output_file, 'w', newline='') as outfile:
writer = csv.writer(outfile)
writer.writerow(selected_columns) # 写入所选列的表头
for row in reader:
selected_row = [row[i] for i in selected_indexes]
writer.writerow(selected_row) # 写入所选列的数据
# 示例用法
input_file = 'input.csv'
output_file = 'output.csv'
selected_columns = ['列名1', '列名2', '列名3']
save_selected_columns(input_file, output_file, selected_columns)
```
在上述代码中,`input_file` 是输入的 CSV 文件路径,`output_file` 是输出的 CSV 文件路径,`selected_columns` 是你想要保存的列的列表。请将代码中的 `'列名1', '列名2', '列名3'` 替换为你要保存的实际列名。
运行该代码后,会读取 `input.csv` 文件中的数据,提取指定的列,并将结果保存到 `output.csv` 文件中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)