Skip to main content
 首页 » 编程设计

python之在将文件导入 SQL Server 2008 之前解析包含随机更改顺序的列的文件的最佳方法

2025年05月04日13zdz8207

我有一个文件,其中的列如下所示:

Column1,Column2,Column3,Column4,Column5,Column6 
1,2,3,4,5,6 
1,2,3,4,5,6 
1,2,3,4,5,6 
1,2,3,4,5,6 
1,2,3,4,5,6 
1,2,3,4,5,6 
Column1,Column3,Column2,Column6,Column5,Column4 
1,3,2,6,5,4 
1,3,2,6,5,4 
1,3,2,6,5,4 
Column2,Column3,Column4,Column5,Column6,Column1 
2,3,4,5,6,1 
2,3,4,5,6,1 
2,3,4,5,6,1 

列在文件中间随机重新排序,了解顺序的唯一方法是查看数据之前的最后一组标题(Column1、Column2 等)(我也简化了数据,以便更容易描绘。在现实生活中,没有办法区分数据,因为它们都是大整数值,可以真正进入任何列)

显然,在使用 BULK INSERT 时,这对 SQL Server 不是很友好,因此我需要找到一种方法,以与我的 SQL 数据库中表的列顺序相匹配的一致顺序排列所有列。最好的方法是什么?我听说 Python 是要使用的语言,但我从未使用过它。任何语言的任何建议/示例脚本都将受到赞赏。

请您参考如下方法:

python 中的解决方案:

我会逐行阅读并查找标题。当我找到标题时,我用它来计算顺序(以某种方式)。然后我将该订单传递给 itemgetter,它将执行重新排序元素的魔法:

from operator import itemgetter 
def header_parse(line,order_dict): 
    header_info = line.split(',') 
    indices = [None] * len(header_info) 
    for i,col_name in enumerate(header_info): 
        indices[order_dict[col_name]] = i 
    return indices 
 
def fix(fname,foutname): 
    with open(fname) as f,open(foutname,'w') as fout: 
        #Assume first line is a "header" and gives the order to use for the 
        #rest of the file 
        line = f.readline() 
        order_dict = dict((name,i) for i,name in enumerate(line.strip().split(','))) 
        reorder_magic = itemgetter(*header_parse(line.strip(),order_dict)) 
        for line in f: 
            if line.startswith('Column'):  #somehow determine if this is a "header" 
                reorder_magic = itemgetter(*header_parse(line.strip(),order_dict)) 
            else: 
                fout.write(','.join(reorder_magic(line.strip().split(','))) + '\n') 
 
if __name__ == '__main__': 
    import sys 
    fix(sys.argv[1],sys.argv[2]) 

现在你可以称它为:

python fixscript.py badfile goodfile