#!/usr/bin/env python
from struct import *
import os
import sys
def exactStock(fileName, code):
ofile = open(fileName, 'rb')
buf = ofile.read()
ofile.close()
num = len(buf)
no = num / 32
b = 0
e = 32
items = list()
for i in range(int(no)):
a = unpack('IIIIIfII', buf[b:e])
year = int(a[0] / 10000)
m = int((a[0] % 10000) / 100)
month = str(m)
if m < 10:
month = "0" + month
d = (a[0] % 10000) % 100
day = str(d)
if d < 10:
day = "0" + str(d)
dd = str(year) + "-" + month + "-" + day
openPrice = a[1] / 100.0
high = a[2] / 100.0
low = a[3] / 100.0
close = a[4] / 100.0
amount = a[5]
vol = a[6]
unused = a[7]
if i == 0:
preClose = close
ratio = round((close - preClose) / preClose * 100, 2)
preClose = close
item = [code, dd, str(openPrice), str(high), str(low), str(close), str(ratio), str(amount), str(vol)]
items.append(item)
b = b + 32
e = e + 32
return items
#exactStock('I:\\e\\tdx\\NEW PTTQ V12(5.90S)\\vipdoc\sh\\lday\\sh000001.day', "000001")
def day2csv_data(dirname, fname, targetDir):
ofile = open(dirname + os.sep + fname, 'rb')
buf = ofile.read()
ofile.close()
ifile = open(targetDir + os.sep + fname + '.csv', 'w')
num = len(buf)
no = num / 32
b = 0
e = 32
line = ''
linename = str('date') + ',' + str('open') + ', ' + str('high') + ' ,' + str('low') + ', ' + str(
'close') + ' ,' + str('amout') + ', ' + str('vol') + ' ,' + str('str07') + '' + '\n'
# print line
ifile.write(linename)
# for i in xrange(no):
for i in range(int(no)):
a = unpack('IIIIIfII', buf[b:e])
line = str(a[0]) + ',' + str(a[1] / 100.0) + ', ' + str(a[2] / 100.0) + ' ,' + str(a[3] / 100.0) + ', ' + str(
a[4] / 100.0) + ' ,' + str(a[5]) + ', ' + str(a[6]) + ' ,' + str(a[7]) + '' + '\n'
# print line
ifile.write(line)
b = b + 32
e = e + 32
ifile.close()
# pathdir='/vipdoc/sh/lday'
pathdir = 'F:\\python\\untitled1\\core\\data'
# targetDir='/_python_gp_tdx/data_gupiao/sh/lday'
targetDir = 'F:\\python\\untitled1\\core\\data'
listfile = os.listdir(pathdir)
for f in listfile:
day2csv_data(pathdir, f, targetDir)
else:
print('The for ' + pathdir + ' to ' + targetDir + ' loop is over')
参考来源:https://blog.csdn.net/liuyukuan/article/details/53560278?utm_source=blogxgwz2