---
title: "用python的xlrd库分拣四六级照片"
url: "https://lerry.me/post/2011/03/sorting-photos-with-python"
date: 2011-03-28T12:22:00.000Z
updated: 2026-08-31T10:40:50.370Z
tags:
  - "Python"
language: zh-CN
---

# 用python的xlrd库分拣四六级照片

由于略懂计算机，于是每当有各种考试报名，信息收集，老师就会找我做，郁闷……         
幸好我会一点编程，呵呵，可以用编程简化很多操作，比如这次四六级报名要分拣照片，由于9个班的照片是放在一起的，报名时四级和六级报考者的照片要分开放，于是我就做了这个小脚本。

功能：
---

1.使用xlrd从四六级报名表读取学号，姓名
----------------------

2011年6月份四级考试报名表

序号

学号

姓名

班级

等级

1

090120001

张三

09普英一班

四级

2.根据学号把photo文件下以学号命名的照片复制到tem4或者tem6文件夹
---------------------------------------

代码如下：

```python
# -*- coding: utf-8 -*-
import os,shutil as s
import xlrd
xlsfile = 'test.xls'
photos = 'photo'
temphoto=['tem4','tem6']
for photodir in temphoto:
    if not os.path.exists(photodir):
        os.mkdir(photodir)
data = xlrd.open_workbook(xlsfile)
table1 = data.sheets()[0]
table2 = data.sheets()[1]
tem4ids = table1.col_values(1)
tem4names = table1.col_values(2)
tem6ids = table2.col_values(1)
tem6names = table2.col_values(2)
f1 = open('tem4log.txt','w')
for id in tem4ids:
    try:
        s.copy(photos+'\\'+str(id)+'.jpg',temphoto[0])
    except:
        f1.write(tem4names[tem4ids.index(id)].encode('UTF-8')+'   学号'+str(id)+'没有照片'+'\n')
        #f1.write(str(id)+'Have no photo'+'\n')   

f2 = open('tem6log.txt','w')        
for id in tem6ids:
    try:
        s.copy(photos+'\\'+str(id)+'.jpg',temphoto[1])
    except:
        f2.write(tem6names[tem6ids.index(id)].encode('UTF-8')+'   学号'+str(id)+'没有照片'+'\n')
        #f2.write(str(id)+'Have no photo'+'\n')
```
