Detailed explanation of document automation processing of Python automation

  • 2021-11-13 02:17:09
  • OfStack

1. Generate random test paper files

If you are a geography teacher with 35 students in your class, you want to take a quiz in the capitals of each state in the United States. Unfortunately, there are several bad guys in the class, so you can't be sure that the students won't cheat. You want to change the order of the questions randomly so that each paper is one-size-fits-all, so that no one can copy the answers from others. Of course, it is time-consuming and boring to finish it by hand.
Here's what the program does:

Create 35 different test papers.

Create 50 multiple-choice questions for each test paper in random order.

Provide 1 correct answer and 3 random wrong answers for each question in random order.

Write the test paper into 35 text files.

Write the answers to 35 text files.

This means that the code needs to do the following:

Keep the states and their capitals in a dictionary.

• Call open (), write (), and close () for the quiz text file and the answer text file.

Use random. shuffle () to randomly adjust the order of questions and multiple options.

Code:


import random

# The data of the question is stored in the dictionary, with the name of the poem as the key and the author as the value. 
poems={'1+3':'4',
'6+7':'13',
'9*3':'27',
'40-1':'39',
'38-13':'25'

}
# We can use the dictionary above to randomly list 5 A test paper 
for num in range(5):
     # Create text files for test papers and answers 
     testFile = open('poem_test%s.txt' % (num + 1),'w')
     answerFile = open('poem_answer%s.txt' % (num + 1),'w')

     # Create the header format of the test paper 
     testFile.write(' Name: \n\n Date: \n\n Grade: \n\n')
     testFile.write(' Test paper number: %s' %(num + 1))
     testFile.write('\n\n\n')

     # Randomly get the name of a poem 
     names = list(poems.keys())
     random.shuffle(names)
# Create Answer Options , This for Loop is to be included on it 1 A for In the loop, because oh, we need to do it for every 1 File creation options. 

 for questionNum in range(10):
          # The correct choice of the test paper is names The author of the value in the list corresponding to the dictionary 
          correctAnswer = poems[names[questionNum]]
          # The wrong choice in the test paper is all the values in the dictionary 
          # Then remove the correct one during each loop 1 Item, 
          wrongAnswers = list(poems.values())
          del wrongAnswers[wrongAnswers.index(correctAnswer)]
          # Random selection 3 A wrong answer 
          #random Medium sample(seq, n) Function: From sequence seq Select in n Random and independent elements; 
          wrongAnswers = random.sample(wrongAnswers,3)
          # What the questionnaire contains 4 Options 
          answerOptions = wrongAnswers + [correctAnswer]
          # Disturb the order of answers 
          random.shuffle(answerOptions)

# No. 1 4 Step: Write the contents to the test paper and answer file 
# Write questions and answers to a file, \ Denote 1 You can change more than one line of code if you can't write it 
          testFile.write('%s,%s The answer is :\n' % \
                         (questionNum + 1,names[questionNum]))
          for i in range(4):
               testFile.write('%s. %s\n'%('ABCD'[i],answerOptions[i]))
          testFile.write('\n')

          # Write the answer 
          answerFile.write('%s.%s\n' % (questionNum + 1,'ABCD'\
                                        [answerOptions.index(correctAnswer)]))
     testFile.close()
     answerFile.close() 



2. Create and write a new file using Python

This section describes how to use programs to organize files that already exist on your hard disk. I don't know if you've ever been looking for a folder with dozens, hundreds or even thousands of files that need to be copied, renamed, moved or compressed manually. For example, the following tasks:

In 1 folder and all its subfolders, copy all pdf files (and only pdf files)

• Remove the leading zero in the file name for all files in a folder that contains hundreds of files named spam001.txt, spam002.txt, spam003. txt, and so on.

Zip the contents of several folders into an ZIP file (this may be a simple backup system)

All this boring task is to request automation with Python. By programming your computer to accomplish these tasks, you turn it into a fast-working document clerk who never makes mistakes.

get_all_file_by_type (): According to the received path and type, all files ending in type type under the path are obtained get_all_file_by_string (): According to the received path and list, all the files under the path containing the string in list are obtained copy_file_by_type (): The get_all_file_by_type () method is called based on the received old_path and type. Select different execution codes according to conditions copy_file_by_string (): The same, except that it calls the get_all_file_by_string () method

#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对该文件夹的文件批量复制到另1个指定文件夹中。有两种模式,1种只复制文件。第2种复制文件的完整路径

import os
import shutil

def get_all_file_by_type(path, type=()):  # 获得以type类型结尾的所有文件,返回1个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)  # 将1个完整路径中,开始的路径替换成新的路径
                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)  # 与上述1样,只不过这里调用的是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), write a program that traverses a directory tree to find files with specific extensions (such as. pdf or. jpg). Copy these files to a new folder regardless of their location.

2), 1 Some unnecessary, huge files or folders take up the hard disk space, this is not uncommon. If you try to free up space on your computer, deleting unwanted huge files works best. But first you have to find them. Write a program, traversing a directory tree, looking for particularly large files or folders, for example, more than 100MB files (recall 1, to get the size of the file, you can use os module os.path.getsize() ). Print the absolute paths of these files to the screen.

3), write a program, in a folder, find all the files with the specified prefix, such as spam001. txt, spam002. txt, etc., and locate the missing number (for example, spam001. txt and spam003. txt exist, but spam002. txt do not exist). Let the program rename all subsequent files and eliminate missing numbers. As an additional challenge, write another program to vacate 1 number among 1 serial number files so that new files can be added.


Related articles: