使用不同格式字符串时,Python struct.Struct.unpack_from的困难
这是我第一次发帖,之前一直在潜水。我到处寻找答案,但现在真的到了需要求助的地步…!
我在实现John Machin对一个旧问题的回答时遇到了一些麻烦:
简单来说,我正在使用这段代码来拆分固定格式的文本文件,并将它们导入到PostgreSQL数据库中。我已经成功地用这段代码处理了一个文本文件,但现在我想扩展我的程序,让它能处理不同格式的文本文件,结果不断遇到同样的错误:
struct.error: unpack_from requires a buffer of at least [x] bytes
当然,根据我传给函数的格式字符串,x的值会有所不同——我的问题是,这段代码只对一种格式有效,其他格式都不行。我唯一改变的就是用来计算格式字符串的变量,以及脚本中与格式相关的变量名。
举个例子,这段代码运行得很好:
cnv_text = lambda s: str(s.strip())
cnv_int = lambda s: int(s) if s.isspace() is False else s.strip()
cnv_date_ymd = lambda s: datetime.datetime.strptime(s, '%Y%m%d') if s.isspace() is False else s.strip() # YYYY-MM-DD
unpack_len = 0
unpack_fmt = ""
splitData = []
conn = psycopg2.connect("[connection info]")
cur = conn.cursor()
Table1specs = [
('A', 6, 14, cnv_text),
('B', 20, 255, cnv_text),
('C', 275, 1, cnv_text),
('D', 276, 1, cnv_text),
('E', 277, 1, cnv_text),
('F', 278, 1, cnv_text),
('G', 279, 1, cnv_text),
('H', 280, 1, cnv_text),
('I', 281, 8, cnv_date_ymd),
('J', 289, 8, cnv_date_ymd),
('K', 297, 8, cnv_date_ymd),
('L', 305, 8, cnv_date_ymd),
('M', 313, 8, cnv_date_ymd),
('N', 321, 1, cnv_text),
('O', 335, 2, cnv_text),
('P', 337, 2, cnv_int),
('Q', 339, 5, cnv_int),
('R', 344, 255, cnv_text),
('S', 599, 1, cnv_int),
('T', 600, 1, cnv_int),
('U', 601, 5, cnv_int),
('V', 606, 10, cnv_text)
]
#for each column in the spec variable...
for column in Table1specs:
start = column[1] - 1
end = start + column[2]
if start > unpack_len:
unpack_fmt += str(start - unpack_len) + "x"
unpack_fmt += str(end - start) + "s"
unpack_len = end
field_indices = range(len(Table1specs))
print unpack_len, unpack_fmt
#set unpacker
unpacker = struct.Struct(unpack_fmt).unpack_from
class Record(object):
pass
filename = "Table1Data.txt"
f = open(filename, 'r')
for line in f:
raw_fields = unpacker(line)
r = Record()
for x in field_indices:
setattr(r, Table1specs[x][0], Table1specs[x][3](raw_fields[x]))
splitData.append(r.__dict__)
所有数据都被添加到splitData中,然后我在一个循环中处理这些数据,生成SQL语句,通过psycopg2输入到数据库中。当我把规格改成其他格式(同时也修改其他相关变量)时,就会出现错误。错误发生在'raw_fields = unpacker(line)'这一行。
我已经用尽了所有资源,现在感到无从下手…欢迎任何想法或建议。
(这可能和我导入的文本文件有关吗?)
最好的祝福。
1 个回答
1
我已经解决了这个问题:问题出在我正在解析的文本文件上。文件中的行太短了,所以我写了一个函数,给每一行的末尾加上空格,让它们变得足够长:
def checkLineLength(checkFile, minLength):
print ('Checking length of lines in file '+ checkFile+', where minimum line length is '+str(minLength))
counter = 0
fixedFile = 'fixed'+checkFile
src = open(checkFile, 'r')
dest = open(fixedFile, 'w')
lines = src.readlines()
for line in lines:
if len(line) < minLength:
x = (line.rstrip('\r\n') + (" "*(minLength-(len(line)-1))+'\r\n'))
dest.write(x)
counter += 1
else:
dest.write(line)
if counter > 0:
os.remove(checkFile)
os.rename(fixedFile, checkFile)
print (str(counter) + " lines fixed in "+ checkFile)
else:
print('Line length in '+checkFile+' is fine.' )
os.remove(fixedFile)