python for循环遍历学生全部答题卡,读取word生成时间,形成word文件名与时间的字典
时间: 2023-06-10 19:07:34 浏览: 59
假设学生答题卡的文件名格式为 "student_1.docx", "student_2.docx", ...,可以使用以下代码实现:
```python
import os
import docx
from datetime import datetime
# 学生答题卡所在目录
dir_path = "/path/to/student/answer/papers/"
# 遍历目录下所有docx文件
word_files = [f for f in os.listdir(dir_path) if f.endswith('.docx')]
# 用字典存储word文件名和生成时间
word_time_dict = {}
for file in word_files:
# 读取docx文件
doc = docx.Document(os.path.join(dir_path, file))
# 获取生成时间
create_time = doc.core_properties.created
# 将生成时间转换为字符串格式
create_time_str = create_time.strftime("%Y-%m-%d %H:%M:%S")
# 将文件名和生成时间存入字典
word_time_dict[file] = create_time_str
print(word_time_dict)
```
运行以上代码后,会输出一个字典,字典的键为学生答题卡的文件名,值为该文件的生成时间,示例输出如下:
```
{
'student_1.docx': '2022-01-01 08:00:00',
'student_2.docx': '2022-01-02 09:00:00',
'student_3.docx': '2022-01-03 10:00:00',
...
}
```
注意,该代码需要安装 `docx` 库才能正确运行,可以使用以下命令安装:
```
pip install python-docx
```