懵懂的菜鸟

Stay hungry,Stay foolish.

导航

python 文件合并和编号

 1 # -*- coding:utf-8 -*-
 2 import os
 3 import re
 4 p1=r"([0-9][0-9][AB])\.\w{3}$"
 5 pattern1=re.compile(p1)
 6 def get_dir(zz):
 7     listdir=[]
 8     for filename in os.listdir('./%s'%zz):
 9         listdir.append(filename)
10         # print(filename)
11         # print(type(filename))
12     # print(listdir)
13     return listdir
14 
15 def joint_b0(listdir,zz):
16     if not os.path.exists('./new/'):
17         os.makedirs('./new/')
18     fw=open('./new/%s.csv'%(zz),'a')
19     for i in listdir:
20         # print(i)
21         j=1000
22         matcher1=re.findall(pattern1,i)
23         fr=open('./%s/%s'%(zz,i))
24         for line in fr.readlines():
25             try:
26                 # print(len(line))
27                 if(len(line)==1):
28                     continue
29                 else:
30                     fw.write(matcher1[0]+'_%s'%j+','+line.strip('\n')+'\n')
31                     j=j+1
32             except:
33                 pass
34     fr.close()
35     fw.close()    
36 
37 def joint_b1(listdir,zz):#单独拼接
38     if not os.path.exists('./new/'):
39         os.makedirs('./new/')
40     fw=open('./new/%s.csv'%(zz),'a')
41     for i in listdir:
42         # print(i)
43         j=1
44         matcher1=re.findall(pattern1,i)
45         fr=open('./%s/%s'%(zz,i))
46         for line in fr.readlines():
47                 fw.write(line)
48 
49     fr.close()
50     fw.close()    
51 if __name__=="__main__":
52 
53     # dir_list=['b0'],'b3','b4','b2_idsd','b3_idcd'
54 
55 
56     dir_list=['b4']#用于编号和拼接,会在new目录下生成编号号码的文件
57     for i in range(len(dir_list)):
58         listdir=get_dir(dir_list[i])
59         # print(listdir)
60         joint_b0(listdir,dir_list[i])
61 
62     # dir_list=['stock']#用于拼接,将需要拼接的放到stock目录下,会在new目录下生成stock文件,然后根据需要修改名称
63     # for i in range(len(dir_list)):
64     #     listdir=get_dir(dir_list[i])
65     #     # print(listdir)
66     #     joint_b1(listdir,dir_list[i])

 

posted on 2017-08-29 18:03  懵懂的菜鸟  阅读(326)  评论(0编辑  收藏  举报