You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:在CSV文件指定列添加数据且不覆盖原有内容

嘿,我一眼就揪出问题所在啦——你打开文件用的是'w'写入模式!这个模式会直接清空目标文件的所有原有内容,然后从头开始写入新数据,难怪之前的值都没了!

另外你的代码里还有个隐藏小bug:你一开始定义了hour = datetime.datetime.now().strftime("%H"),后面又用for hour in range(24 + 1):,这会把之前的当前小时变量直接覆盖,导致你写入的小时列可能根本不是你想要的那个时间点,得赶紧改了。

下面根据你的真实需求分两种场景给你解决方案:

场景1:给已有CSV追加新的城市数据行

如果你的需求是新增行(比如添加新城市的当前小时温度),可以这么改:

import csv
import datetime
import os

# 拆分变量名,避免冲突
current_month = datetime.datetime.now().strftime("%B")
current_day = datetime.datetime.now().strftime("%d")
current_hour = datetime.datetime.now().strftime("%H")
file_path = f'{current_month}_{current_day}.csv'

# 定义所有列名
labels = ['city'] + [str(h) for h in range(24 + 1)]

# 检查文件是否已存在
file_exists = os.path.isfile(file_path)

with open(file_path, 'a', encoding='utf-8', newline='') as file:
    writer = csv.DictWriter(file, fieldnames=labels, extrasaction='ignore', delimiter=';')
    
    # 只有文件不存在时才写入表头,避免重复
    if not file_exists:
        writer.writeheader()
    
    # 写入数据(这里假设city和temperature是你已处理好的数组)
    for city_item, temp_item in zip(city, temperature):
        row_data = {
            'city': city_item[0].text,
            current_hour: temp_item.text
        }
        writer.writerow(row_data)

这里用'a'(追加)模式打开文件,只会在文件末尾加新内容,不会清空原有数据。

场景2:更新已有行的指定列数据

如果你的需求是给已有的城市行补充某小时的温度(比如原有行已经有city和部分小时数据,现在填充当前小时的值),那得先读取原有数据,更新后再重新写入:

import csv
import datetime
import os

current_month = datetime.datetime.now().strftime("%B")
current_day = datetime.datetime.now().strftime("%d")
current_hour = datetime.datetime.now().strftime("%H")
file_path = f'{current_month}_{current_day}.csv'

labels = ['city'] + [str(h) for h in range(24 + 1)]
existing_data = []

# 如果文件存在,先读取所有原有数据
if os.path.isfile(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        reader = csv.DictReader(file, delimiter=';')
        existing_data = list(reader)

# 更新数据:匹配城市,填充对应小时的温度
for city_item, temp_item in zip(city, temperature):
    city_name = city_item[0].text
    temp_value = temp_item.text
    # 查找是否已有该城市的行
    found = False
    for row in existing_data:
        if row['city'] == city_name:
            row[current_hour] = temp_value
            found = True
            break
    # 没有找到的话就新增一行
    if not found:
        new_row = {col: '' for col in labels}
        new_row['city'] = city_name
        new_row[current_hour] = temp_value
        existing_data.append(new_row)

# 重新写入整个文件(这里用'w'但不会丢数据,因为已经把原有内容读进来了)
with open(file_path, 'w', encoding='utf-8', newline='') as file:
    writer = csv.DictWriter(file, fieldnames=labels, extrasaction='ignore', delimiter=';')
    writer.writeheader()
    writer.writerows(existing_data)

最后再划个重点:

  • 'w'模式=清空重写,适合需要修改原有行的场景;
  • 'a'模式=末尾追加,适合新增行的场景;
  • 变量名一定要区分开,别像之前那样把当前小时和循环变量搞混了!

内容的提问来源于stack exchange,提问作者vlado_sl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 13:57:26