
基本读写操作
Python内置的文件操作函数足以应对保存股票代码的需求。写入时,使用open()函数以写入模式打开文件,调用write()方法将股票代码逐行写入。读取时,以只读模式打开,通过readlines()或迭代逐行获取代码。
# 写入股票代码到txt文件
stock_codes = ['600519', '000001', '601318']
with open('stocks.txt', 'w') as f:
for code in stock_codes:
f.write(code + '\n')
# 读取股票代码
with open('stocks.txt', 'r') as f:
codes = [line.strip() for line in f if line.strip()]
print(codes)
这种方式的优势在于简单直接,无需额外安装库。txt文件可以轻松地用文本编辑器查看和修改。但股票代码较多或需要频繁更新时,手动维护文件内容并不高效。

追加与去重
实际应用中,往往需要不断添加新的股票代码。以追加模式'a'打开文件,可以避免覆盖原有内容。为避免重复代码,可以在写入前读取现有代码,用集合去重后再写入。
# 追加新代码并去重
def add_stock(code_to_add):
with open('stocks.txt', 'r') as f:
existing = {line.strip() for line in f}
if code_to_add not in existing:
with open('stocks.txt', 'a') as f:
f.write(code_to_add + '\n')
print(f'Added {code_to_add}')
else:
print(f'{code_to_add} already exists')
add_stock('000002')
add_stock('600519') # 已存在
去重操作在每次添加时都读取整个文件,对于大量数据可能效率不高。若需要频繁添加且数据量巨大,可以考虑使用数据库或专门的存储格式,比如JSON、CSV,或者直接使用Python的shelve模块。
批量处理与格式化
股票代码有时需要特定格式,如统一为6位数字,不足补零。写入前可对代码进行格式化。批量写入时,使用循环或列表推导式可以简化代码。
# 格式化并批量写入
raw_codes = ['600519', '1', '300750'] # '1'应格式化'000001'
formatted = [code.zfill(6) for code in raw_codes]
with open('stocks.txt', 'w') as f:
f.writelines([code + '\n' for code in formatted])
需要注意,股票代码在不同市场可能长度不同,如美股代码为字母,港股为5位数字。保存时,根据需求选择合适的验证规则,避免无效代码进入文件。
使用第三方库和工具
对于股票数据获取和存储,常与pandas、yfinance等库配合。pandas可以直接从txt读取至DataFrame,但需要明确分隔符。例如,用逗号分隔代码和名称。
import pandas as pd
# 假设txt内容:代码,名称
df = pd.read_csv('stocks.txt', header=None, names=['code', 'name'])
print(df.head())
写入DataFrame到txt:
df.to_csv('stocks.txt', index=False, sep=',', header=False)
这种结构化存储更利于后续数据处理,比如过滤、排序。
处理相关交易数据
股票交易中,不仅保存代码,还需关联价格、持仓等。txt文件适合简单列表,如每日监控的股票池。但若需要频繁更新价格,保存为其它格式更优。
# 保存股票代码及最新价格
data = {'600519': 1800.0, '000001': 12.5}
with open('prices.txt', 'w') as f:
for code, price in data.items():
f.write(f'{code},{price}\n')
这种格式可被Excel打开,也便于pandas读取。
错误与异常处理
文件操作可能遇到权限问题、磁盘满等异常。在代码中加入try-except可以保证程序稳定。
try:
with open('stocks.txt', 'a') as f:
f.write('600001\n')
except IOError as e:
print(f'写入失败: {e}')
处理不存在的文件时,读取会引发FileNotFoundError,可以先行判断文件是否存在,或捕获异常。
实际案例:管理股票池
假设每日监控一批股票,需要将观察列表存储在txt中,每周更新。
import os
file_name = 'watchlist.txt'
# 若文件不存在,初始化
if not os.path.exists(file_name):
with open(file_name, 'w') as f:
f.write('600519\n000001\n')
# 添加新股票,去除旧股票
def update_watchlist(new_codes):
# 读取现有
with open(file_name, 'r') as f:
current = [line.strip() for line in f if line.strip()]
# 合并并去重
updated = list(set(current) | set(new_codes))
# 写入
with open(file_name, 'w') as f:
for code in updated:
f.write(code + '\n')
return updated
new_codes = ['601318', '000002']
print(update_watchlist(new_codes))
此案例展示了如何应对动态变化。
高级选项:使用Python内置的shelve
对于需要保存股票代码及其属性的用户,shelve提供了类似字典的持久化,但不依赖数据库。
import shelve
with shelve.open('stocks_data') as db:
db['codes'] = ['600519', '000001']
db['prices'] = {'600519': 1800.0}
# 读取
with shelve.open('stocks_data') as db:
codes = db['codes']
print(codes)
shelve保存为三个文件,更适合结构化数据。
保存路径与目录
在项目中,文件路径可能不在当前工作目录。使用绝对路径或构建路径。
from pathlib import Path
# 指定目录
path = Path('data') / 'stocks.txt'
path.parent.mkdir(exist_ok=True) # 创建目录
with open(path, 'w') as f:
f.write('600519\n')
性能与大数据量
若股票代码数量达上万,每次写入都打开文件会较慢。一次性写入所有数据是更好的选择。
codes_large = [f'{i:06d}' for i in range(100000)] # 模拟10万个代码
with open('large_stocks.txt', 'w') as f:
f.write('\n'.join(codes_large))
用join一次性构建字符串,比逐行write快得多。但内存占用可能高,可分批写入。
使用txt保存股票代码是一种轻量级的持久化方案。关键在于读写操作的正确性、去重逻辑、以及格式化。若需与行情数据联动,可结合pandas和结构化文本。合理使用路径和异常处理,能让程序更具健壮性。最终,选择哪种方式取决于项目的复杂度和性能要求。