小白开始记录自己的代码之路
第一天实习,交给了我55个表格,要求把身份证号和序号全部粘贴到新的表格里。做了2个小时,接下来又是55个表格…于是燃起了编程的欲望。
学过一些些基础的python,于是决定用python试试。
绝对保姆级教程。适合超级超级新手。(也就是说很啰嗦… …)
注意代码,新建表格和要读取的表格都要放到一个目录下,不然要加路径。
应用的是anaconda 的 Spyder
1.导入新表
第一步准备先试试把一个表格的内容全部导入新的表格中,相当于全部复制粘贴。
lines = open('表格名称.csv','r',encoding='gbk').readlines()
n = ''
for line in lines:
n = n+line
with open('new form 1.csv','w',encoding='gbk') as new_f:
new_f.write(n)
new_f.close()
第一步成功
2.读取特定名称的列
我发现了两个神仙模块,xlrd和xlwt,专门用来读写excel的,这样就不用再转换csv文件格式了。
直接在windows键+R输入cmd,然后
pip install xlrd
pip install xlwt
就行了
好的我们继续。
先读一下身份证号和序号试试
import xlrd
# 打开excel文件,创建一个workbook对象,book对象也就是表格名称.xlsx文件,表含有sheet名
rbook = xlrd.open_workbook('表格名称.xlsx')
rbook.sheets() # xls默认有3个工作簿,Sheet1,Sheet2,Sheet3
rsheet = rbook.sheet_by_index(0) # 取第一个工作簿
# 循环工作簿的所有行
for row in rsheet.get_rows():
ID_column = row[2] # 身份证号所在的列
ID_value = ID_column.value # 项目名
if ID_value != '身份证号': # 排除第一行
number_column = row[0] # 价格所在的列
number_value = number_column.value
print("身份证号", ID_value, "序号", number_value)
运行后右侧会出来表格里的所有身份证号和序号。
3.读取特定名称的列并写入新表格
接下来我们尝试写入新的表格,按照身份证号在左,序号在右的顺序。
啊这一步卡了好久… …
先试着写个身份证号,一列
import xlrd
import xlwt
rbook = xlrd.open_workbook('表格名称.xlsx')
rbook.sheets()
rsheet = rbook.sheet_by_index(0)
cols = rsheet.col_values(2)[2:] #取第三列,从第三行开始
n = 0
xls = xlwt.Workbook()
sheet = xls.add_sheet('sample') #创建一个新的sample表格
for col in cols:
sheet.write(n,0,col)
n = n+1
xls.save('sample.xls')
运行结果出来的时候感动死我了,毕竟是一个要困死的人,一下子就精神了!一鼓作气继续!
import xlrd
import xlwt
rbook = xlrd.open_workbook('表格名称.xlsx')
rbook.sheets()
rsheet = rbook.sheet_by_index(0)
cols = rsheet.col_values(2)[2:]
colums = rsheet.col_values(0)[2:]
n = 0
m = 0
xls = xlwt.Workbook()
sheet = xls.add_sheet('sample')
for col in cols:
sheet.write(n,0,col)
n = n+1
for colum in colums:
sheet.write(m,1,colum)
m = m+1
xls.save('sample.xls')
开心!接下来只要能把所有表格弄到一起就行了。
4.两个表格的合并
先做两个表的,以防翻车。
首先要读取特定文件夹的表格,记得代码要存在文件夹里
import os
filelist=[]
for root, dirs, files in os.walk(".", topdown=False):
for name in files:
str=os.path.join(root, name)
if str.split('.')[-1]=='xlsx':
filelist.append(str)
用一个print (x)就能看到x是文件夹里所有以.xlsx结尾的文件的名称。