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

如何将Python程序输入的数据保存到外部文件且不覆盖原有内容

Python输入数据持久化存储实现方案

实现将用户输入内容保存到本地文件、重启程序可读取、新增数据不覆盖原有内容的需求,可根据使用场景选择以下几种方案:

方案1:基础文本追加写入(适合纯文本简单存储)

直接使用文件追加模式a写入内容,操作最简单,适合仅存储单行文本的场景:

# 获取用户输入
name = str(input("Register person: "))

# 追加模式打开文件,文件不存在会自动创建,不会覆盖原有内容
with open('person_records.txt', 'a', encoding='utf-8') as f:
    # 写入时加换行符避免多条数据挤在同一行
    f.write(name + '\n')

# 读取所有已保存的人员数据
with open('person_records.txt', 'r', encoding='utf-8') as f:
    person_list = [line.strip() for line in f if line.strip()]
print(person_list)

方案2:JSON存储结构化数据(适合存储字典/列表等复杂结构)

如果需要存储人员姓名、年龄、联系方式等多字段信息,选择JSON格式更方便后续解析处理:

import json
import os

# 获取用户输入,可按需扩展其他字段
name = str(input("Register person: "))
new_person = {"name": name}

record_file = 'person_records.json'
# 先读取原有数据,文件不存在则初始化空列表
if os.path.exists(record_file):
    with open(record_file, 'r', encoding='utf-8') as f:
        person_list = json.load(f)
else:
    person_list = []

# 追加新数据后写回文件
person_list.append(new_person)
with open(record_file, 'w', encoding='utf-8') as f:
    # ensure_ascii=False保证中文正常存储,indent=2提升文件可读性
    json.dump(person_list, f, ensure_ascii=False, indent=2)

# 读取验证所有数据
with open(record_file, 'r', encoding='utf-8') as f:
    all_persons = json.load(f)
print(all_persons)

方案3:CSV格式存储(适合表格类数据,支持Excel直接打开)

如果需要存储表格类数据,后续要做批量统计或用办公软件打开,可选择CSV格式:

import csv
import os

name = str(input("Register person: "))
record_file = 'person_records.csv'
file_exists = os.path.exists(record_file)

# 追加模式写入
with open(record_file, 'a', encoding='utf-8', newline='') as f:
    writer = csv.writer(f)
    # 首次创建文件时写入表头
    if not file_exists:
        writer.writerow(['人员姓名'])
    writer.writerow([name])

# 读取所有已保存数据
with open(record_file, 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

方案4:shelve模块存储(类字典操作,无需手动序列化)

Python内置shelve模块操作逻辑和普通字典完全一致,自动完成持久化,适合小体量数据快速存储:

import shelve

name = str(input("Register person: "))
# 打开shelve数据库文件,默认支持读写不覆盖
with shelve.open('person_db') as db:
    # 初始化存储列表
    if 'person_list' not in db:
        db['person_list'] = []
    # 追加新数据
    person_list = db['person_list']
    person_list.append(name)
    db['person_list'] = person_list

# 读取验证数据
with shelve.open('person_db') as db:
    print(db['person_list'])

注意事项

  • 所有方案默认使用utf-8编码,避免出现中文乱码问题
  • 纯文本追加写入必须使用a模式,w模式会直接清空原有文件内容
  • 结构化数据优先选择JSON或shelve方案,后续读取、修改、查询操作更便捷

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:45:02