详解Python自动化之文件自动化处理


Posted in Python onJune 21, 2021

一、生成随机的测验试卷文件

假如你是一位地理老师, 班上有 35 名学生, 你希望进行美国各州首府的一个小测验。不妙的是,班里有几个坏蛋, 你无法确信学生不会作弊。你希望随机调整问题的次序, 这样每份试卷都是独一无二的, 这让任何人都不能从其他人那里抄袭答案。当然,手工完成这件事又费时又无聊。
下面是程序所做的事:

• 创建 35 份不同的测验试卷。

• 为每份试卷创建 50 个多重选择题,次序随机。

• 为每个问题提供一个正确答案和 3 个随机的错误答案,次序随机。

• 将测验试卷写到 35 个文本文件中。

• 将答案写到 35 个文本文件中。

这意味着代码需要做下面的事:

• 将州和它们的首府保存在一个字典中。

• 针对测验文本文件和答案文本文件,调用 open()、 write()和 close()。

• 利用 random.shuffle()随机调整问题和多重选项的次序。

代码:

import random

#问题的数据保存在字典中,诗歌名称作为键,作者作为值。
poems={'1+3':'4',
'6+7':'13',
'9*3':'27',
'40-1':'39',
'38-13':'25'

}
#我们可以用上面的字典随机的出5份试卷
for num in range(5):
     #创建试卷和答案文本文件
     testFile = open('poem_test%s.txt' % (num + 1),'w')
     answerFile = open('poem_answer%s.txt' % (num + 1),'w')

     #创建试卷的头部格式
     testFile.write('姓名:\n\n日期:\n\n年级:\n\n')
     testFile.write('试卷号:%s' %(num + 1))
     testFile.write('\n\n\n')

     #随机获取诗歌名称
     names = list(poems.keys())
     random.shuffle(names)
#创建答案选项,这个for循环是要包含在上面一个for循环中的,因为哦们需要为每一个文件创建选项。

 for questionNum in range(10):
          #试卷的正确的选项,就是names列表中的值在字典中对应的作者
          correctAnswer = poems[names[questionNum]]
          #试卷的错误的选项,就是字典中所有的值
          #然后在每次循环过程中去掉其中的正确的那一项,
          wrongAnswers = list(poems.values())
          del wrongAnswers[wrongAnswers.index(correctAnswer)]
          #随机选择三个错误的答案
          #random中sample(seq, n)函数:从序列seq中选择n个随机且独立的元素;
          wrongAnswers = random.sample(wrongAnswers,3)
          #问题单包含的四个选项
          answerOptions = wrongAnswers + [correctAnswer]
          #打乱答案顺序
          random.shuffle(answerOptions)

#第四步:将内容写入测验试卷和答案文件
#将问题和答案写入文件中,\表示一行代码写不下可以换多行
          testFile.write('%s,%s的答案是:\n' % \
                         (questionNum + 1,names[questionNum]))
          for i in range(4):
               testFile.write('%s. %s\n'%('ABCD'[i],answerOptions[i]))
          testFile.write('\n')

          #写入答案
          answerFile.write('%s.%s\n' % (questionNum + 1,'ABCD'\
                                        [answerOptions.index(correctAnswer)]))
     testFile.close()
     answerFile.close()

二、使用Python创建并写入新文件

本节将介绍如何用程序组织硬盘上已经存在的文件。不知你是否经历过查找一个文件夹,里面有几十个、几百个、甚至上千个文件,需要手工进行复制、改名、移动或压缩。比如下列这样的任务:

• 在一个文件夹及其所有子文件夹中,复制所有的 pdf 文件(且只复制 pdf 文件)

• 针对一个文件夹中的所有文件,删除文件名中前导的零,该文件夹中有数百个文件,名为 spam001.txt、 spam002.txt、 spam003.txt 等。

• 将几个文件夹的内容压缩到一个 ZIP 文件中(这可能是一个简单的备份系统)

所有这种无聊的任务,正是在请求用 Python 实现自动化。通过对电脑编程来完成这些任务,你就把它变成了一个快速工作的文件职员,而且从不犯错。

  • get_all_file_by_type() :根据接收到的path 和type,获得该path下所有以type类型结尾的文件
  • get_all_file_by_string(): 根据接收到的path 和 list, 获得该path下所有的,包含list 里字符串的文件
  • copy_file_by_type(): 根据接收到的old_path,和type,调用get_all_file_by_type()方法。根据条件选择不同的执行代码
  • copy_file_by_string():同理,不过它调用的是get_all_file_by_string()方法

#python创建并写入新文件,

#python统计特定文件夹下的word和pdf的数量
import glob,os

# path就是你说的特定文件夹
path = r"D:\linshi"

# 这里的pdf可以换成docx
file=glob.glob(os.path.join(path, "*.pdf"))

count = 0

for i in file:
    count = count + 1
    
print(count)
#复制文件的完整路径借助python对该文件夹的文件批量复制到另一个指定文件夹中。有两种模式,一种只复制文件。第二种复制文件的完整路径

import os
import shutil

def get_all_file_by_type(path, type=()):  # 获得以type类型结尾的所有文件,返回一个list

    filelist = []

    for a, b, c in os.walk(path):
        for name in c:
            fname = os.path.join(a, name)
            if fname.endswith(type):
                filelist.append(fname)

    return filelist


def get_all_file_by_string(path, string_list):
    filelist = []

    for a, b, c in os.walk(path):
        for name in c:
            fname = os.path.join(a, name)
            for string in string_list:  # 遍历string_list,如果文件路径中包含string,那么append进filelist
                if string in fname:  # 如果只想要文件名符合条件,把fname换成name即可
                    filelist.append(fname)
                    break

    return filelist


def copy_file_by_type(old_path, new_path, type=('doc', 'docx'), requird_dir=False):
    try:
        file_list = get_all_file_by_type(old_path, type=type)  # 获得该路径下所有的type类型文件

        if not os.path.exists(new_path):  # 创建新的文件夹
            os.makedirs(new_path)

        if not requird_dir:  # 如果仅复制文件
            for file in file_list:
                name = file.split("\\")[-1]  # 获得文件名字

                new_paths = os.path.join(new_path, name)  # 与新路径拼接,获得完整的新路径
                shutil.copy(file, new_paths)
                print(new_paths + "成功")

        if requird_dir:
            for file in file_list:
                name = file.split("\\")[-1]  # 获得文件名字
                new_paths = file.replace(old_path, new_path)  # 将一个完整路径中,开始的路径替换成新的路径
                dir = new_paths.split(name)[0]  # 获得文件夹路径
                if not os.path.exists(dir):  # 创建新文件夹
                    os.makedirs(dir)
                shutil.copy(file, new_paths)
                print(new_paths + "成功")
    except Exception as e:
        print(e)


def copy_file_by_string(old_path, new_path, string_list, requird_dir=False):
    try:
        file_list = get_all_file_by_string(old_path, string_list=string_list)  # 与上述一样,只不过这里调用的是get_all_file_by_string方法

        if not os.path.exists(new_path):
            os.makedirs(new_path)

        if not requird_dir:
            for file in file_list:
                name = file.split("\\")[-1]

                new_paths = os.path.join(new_path, name)
                shutil.copy(file, new_paths)
                print(new_paths + "成功")

        if requird_dir:
            for file in file_list:
                name = file.split("\\")[-1]
                new_paths = file.replace(old_path, new_path)
                print(new_paths)
                dir = new_paths.split(name)[0]
                if not os.path.exists(dir):
                    os.makedirs(dir)
                shutil.copy(file, new_paths)
                print(new_paths + "成功")
    except Exception as e:
        print(e)


if __name__ == '__main__':
    old_path = r"F:\aaaa"
    new_path = r"F:\bbbb"

    list = ["面试", "笔试", "题库", "题目"]
    copy_file_by_string(old_path=old_path, new_path=new_path, string_list=list, requird_dir=False)

    # type = ('docx','doc',"pdf","md")
    # copy_file_by_type(old_path=old_path, new_path=new_path, type=type, requird_dir=True)

#python压缩多个文件到zip格式-zipfile包实例
pip install zipfile
file=r'D:\test.zip'
out_path=r'D:\files'
#遍历files文件夹下的文件,压缩发送
zip_1=zipfile.ZipFile(file,'w')
	for f in os.listdir(out_path):
		zip_1.write(os.path.join(out_path,f),f,zipfile.ZIP_DEFLATED)
zip_1.close()

#python批量删除文件名_Python批量修改文件名
import os, re

while True:

keyword = input("请输入你要删除的字符串:")

if len(keyword)==0 or keyword.isspace():

print("字符串不能为空!")

else:

break

suffix = input("需要筛选的文件名后缀(Enter代表所有):")

fileNames = os.listdir()  #获取当前目录下的所有文件

for file in fileNames:

check = os.path.join(os.path.abspath('.'),file)

if os.path.isfile(check):

if len(suffix)==0 or suffix.isspace():

if keyword in file:

print(file," -> ",file.replace(keyword,''))

os.rename(file,file.replace(keyword,''))

else:

#用正则表达式匹配后缀名

if re.match('.+?\.'+suffix+'$',file) != None and keyword in file:

print(file," -> ",file.replace(keyword,''))

os.rename(file,file.replace(keyword,''))

1)、编写一个程序,遍历一个目录树,查找特定扩展名的文件(诸如.pdf 或.jpg)。不论这些文件的位置在哪里, 将它们拷贝到一个新的文件夹中。

2) 、一些不需要的、 巨大的文件或文件夹占据了硬盘的空间, 这并不少见。如果你试图释放计算机上的空间, 那么删除不想要的巨大文件效果最好。但首先你必须找到它们。编写一个程序, 遍历一个目录树, 查找特别大的文件或文件夹, 比方说, 超过100MB 的文件(回忆一下,要获得文件的大小,可以使用 os 模块的 os.path.getsize())。将这些文件的绝对路径打印到屏幕上。

3)、编写一个程序, 在一个文件夹中, 找到所有带指定前缀的文件, 诸如 spam001.txt,spam002.txt 等,并定位缺失的编号(例如存在 spam001.txt 和 spam003.txt, 但不存在 spam002.txt)。让该程序对所有后面的文件改名, 消除缺失的编号。作为附加的挑战,编写另一个程序,在一些连续编号的文件中,空出一些编号,以便加入新的文件。

到此这篇关于详解Python自动化之文件自动化处理的文章就介绍到这了,更多相关Python文件自动化处理内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python实现逆波兰计算表达式实例详解
May 06 Python
Python中字符串的格式化方法小结
May 03 Python
python 文件操作删除某行的实例
Sep 04 Python
tensorflow训练中出现nan问题的解决
Feb 10 Python
使用pandas read_table读取csv文件的方法
Jul 04 Python
selenium+python自动化测试之鼠标和键盘事件
Jan 23 Python
python单线程下实现多个socket并发过程详解
Jul 27 Python
Python制作词云图代码实例
Sep 09 Python
python pip安装包出现:Failed building wheel for xxx错误的解决
Dec 25 Python
关于python scrapy中添加cookie踩坑记录
Nov 17 Python
python中opencv实现图片文本倾斜校正
Jun 11 Python
深入浅析Django MTV模式
Sep 04 Python
Python Pandas pandas.read_sql_query函数实例用法分析
Jun 21 #Python
Python Pandas pandas.read_sql函数实例用法
Jun 21 #Python
浅谈Python从全局与局部变量到装饰器的相关知识
Jun 21 #Python
Python-OpenCV教程之图像的位运算详解
Python中的套接字编程是什么?
教你如何使用Python开发一个钉钉群应答机器人
详解Python requests模块
Jun 21 #Python
You might like
超神学院:天使彦公认最美的三个视角,网友:我的天使快下凡吧!
2020/03/02 国漫
PHP字符串的递增和递减示例介绍
2014/02/11 PHP
PHP+iFrame实现页面无需刷新的异步文件上传
2014/09/16 PHP
php的GD库imagettftext函数解决中文乱码问题
2015/01/24 PHP
php判断输入是否是纯数字,英文,汉字的方法
2015/03/05 PHP
PHP 双链表(SplDoublyLinkedList)简介和使用实例
2015/05/12 PHP
javascript showModalDialog 多层模态窗口实现页面提交及刷新的代码
2009/11/28 Javascript
js里怎么取select标签里的值并修改
2012/12/10 Javascript
Jquery时间验证和转换工具小例子
2013/07/01 Javascript
angular中使用Socket.io实例代码
2017/06/03 Javascript
基于node.js实现微信支付退款功能
2017/12/19 Javascript
使用JS获取SessionStorage的值
2018/01/12 Javascript
Django+Vue跨域环境配置详解
2018/07/06 Javascript
jQuery实现数字自动增加或者减少的动画效果示例
2018/12/11 jQuery
Vue基础学习之项目整合及优化
2019/06/02 Javascript
vue v-for直接循环数字实例
2019/11/07 Javascript
微信小程序 button样式设置为图片的方法
2020/06/19 Javascript
[55:56]NB vs Infamous 2019国际邀请赛淘汰赛 败者组 BO3 第二场 8.22
2019/09/05 DOTA
利用Python脚本生成sitemap.xml的实现方法
2017/01/31 Python
Python批量生成幻影坦克图片实例代码
2019/06/04 Python
python requests模拟登陆github的实现方法
2019/12/26 Python
python图片剪裁代码(图片按四个点坐标剪裁)
2020/03/10 Python
Python通过getattr函数获取对象的属性值
2020/10/16 Python
浅谈Python xlwings 读取Excel文件的正确姿势
2021/02/26 Python
印度购物网站:TATA CLiQ
2017/11/23 全球购物
国际领先的在线时尚服装和配饰店:DressLily
2019/03/03 全球购物
英国领先的互联网葡萄酒礼品商:Vintage Wine & Port
2019/05/24 全球购物
查询优化的一般准则有哪些
2015/03/08 面试题
物业管理求职自荐信
2013/09/25 职场文书
九年级政治教学反思
2014/02/06 职场文书
文明餐桌行动实施方案
2014/02/19 职场文书
党员个人公开承诺书
2014/08/29 职场文书
工程部文员岗位职责
2015/02/04 职场文书
《一面五星红旗》教学反思
2016/02/23 职场文书
《植物妈妈有办法》教学反思
2016/02/23 职场文书
实例讲解Python中sys.argv[]的用法
2021/06/03 Python