# 读取第一个 CSV 文件 data1 = [] with open('day01改.csv', 'r', encoding='gbk') as file1: reader = csv.DictReader(file1) for row in reader: data1.append(row) # 读取第二个 CSV 文件 data2 = [] with open('app_class.csv', 'r', encoding='gbk') as file2: reader = csv.DictReader(file2) for row in reader: data2.append(row) # 比较两个数据集并保留相同的内容 result = [] for row in data1: for compare_row in data2: if row['appid'] == compare_row['appid']: row['appid']=compare_row['type'] break
时间: 2024-04-16 09:28:37 浏览: 93
根据你提供的代码,以及你的要求将第一个 CSV 文件中的 "appid" 列替换为第二个 CSV 文件中相应行的 "type" 列内容,下面是完整的代码:
```python
import csv
# 读取第一个 CSV 文件
data1 = []
with open('day01改.csv', 'r', encoding='gbk') as file1:
reader = csv.DictReader(file1)
for row in reader:
data1.append(row)
# 读取第二个 CSV 文件
data2 = []
with open('app_class.csv', 'r', encoding='gbk') as file2:
reader = csv.DictReader(file2)
for row in reader:
data2.append(row)
# 比较两个数据集并保留相同的内容
result = []
for row in data1:
for compare_row in data2:
if row['appid'] == compare_row['appid']:
row['appid'] = compare_row['type']
break
result.append(row)
# 将结果写入新的 CSV 文件
fieldnames = data1[0].keys()
with open('result.csv', 'w', newline='', encoding='gbk') as result_file:
writer = csv.DictWriter(result_file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(result)
```
请确保将 `'day01改.csv'` 和 `'app_class.csv'` 替换为实际的文件路径。代码将创建一个名为 `'result.csv'` 的新文件,其中包含第一个 CSV 文件中 "appid" 列替换为第二个 CSV 文件中相应行的 "type" 列内容的结果。
阅读全文