首頁 > 軟體

詳解Python自動化之檔案自動化處理

2021-06-21 16:01:10

一、生成隨機的測驗試卷檔案

假如你是一位地理老師, 班上有 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('姓名:nn日期:nn年級:nn')
     testFile.write('試卷號:%s' %(num + 1))
     testFile.write('nnn')

     #隨機獲取詩歌名稱
     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. %sn'%('ABCD'[i],answerOptions[i]))
          testFile.write('n')

          #寫入答案
          answerFile.write('%s.%sn' % (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檔案自動化處理內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com