备份一个文本处理python代码

昨天一个朋友提了个需求,处理一个excel文档,固定第一列,第二列是第三列编号,使得同一行第三列和第一列内容相同,且对应调整第2列, 还花了一个小时左右,碰到些奇葩问题,比如python重定向报错,windows上不知道怎么解决,懒得搜了,直接写文件。还有就是长数字被excel当成数字,怎么改格式也不行。查了下,输出的时候加了个“\t”就好了。

# -*- coding: utf-8 -*-
"""
Created on Wed Sep 28 17:37:22 2022

@author: Administrator
"""

#思路,先要记录第三列,每列作为一个key,value是一个list,即所有编号,位于第二列
# 输出: 读取第一列每一行,检查是否有对应key的存在,如果有,读取对应list,输出其中一个
# 并且从list删除, list为空,那么 key也删除
# 如果 没有key存在, 直接输出两个逗号


fname = './SJ120220928.csv'
#fname = './test.csv'

allDict = {}

allKey = []

with open(fname,'r+',encoding='utf-8') as f:
    for line in f.readlines(): 
        #print(line[:-1].split(','))
        words = line[:-1].split(',')
        #print('len:', len(words))
        #print(words)
        
        allKey.append(words[0])
        if len(words) > 2 and len(words[1]) > 0:
            allDict.setdefault(words[2],[])
            allDict[words[2]].append(words[1])

        
#print(len(allDict))        

DictIdx = {}

i = 0
with open('./res.csv', 'w+', encoding='utf-8') as f:
    for word in allKey:
        #print('i ', i)
        if allDict.get(word) != None:
            DictIdx.setdefault(word, 0)
            #print('word ', word)
            cnt = len(allDict[word])
            #print("size ", len(allDict[word]))
            if DictIdx[word] < cnt:
                #print('idx ', DictIdx[word])
                #print('now',allDict[word][DictIdx[word]])
                str1 = word+',' + allDict[word][DictIdx[word]] + '\t,' + word
                f.write(str1)
                print(str1)
                DictIdx[word] = DictIdx[word] + 1
            else:
                str1 = word + ",,"
                f.write(str1)
                print(str1)
        else:
            str1 = word +  ",,"
            f.write(str1)
            print(str1)
        i = i+1
        f.write("\n")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值