[python]《Python編程快速上手:讓繁瑣工作自動化》學習筆記3

1. 組織文件筆記(第9章)(代碼下載)

1.1 文件與文件路徑
通過import shutil調用shutil模塊操作目錄,shutil模塊能夠在Python 程序中實現文件複製、移動、改名和刪除;同時也介紹部分os操作文件的函數。常用函數如下:

函數 用途 備註
shutil.copy(source, destination) 複製文件
shutil.copytree(source, destination) 複製文件夾 如果文件夾不存在,則創建文件夾
shutil.move(source, destination) 移動文件 返回新位置的絕對路徑的字符串,且會覆寫文件
os.unlink(path) 刪除path處的文件
os.rmdir(path) 刪除path處的文件夾 該文件夾必須爲空,其中沒有任何文件和文件
shutil.rmtree(path) 刪除path處的文件夾 包含的所有文件和文件夾都會被刪除
os.walk(path) 遍歷path下所有文件夾和文件 返回3個值:當前文件夾名稱,當前文件夾子文件夾的字符串列表,當前文件夾文件的字符串列表
os.rename(path) path處文件重命名

1.2 用zipfile 模塊壓縮文件
通過import zipfile,利用zipfile模塊中的函數,Python 程序可以創建和打開(或解壓)ZIP 文件。常用函數如下:

函數 用途 備註
exampleZip=zipfile.ZipFile(‘example.zip’) 創建一個ZipFile對象 example.zip表示.zip 文件的文件名
exampleZip.namelist() 返回ZIP 文件中包含的所有文件和文件夾的字符串的列表
spamInfo = exampleZip.getinfo(‘example.txt’) 返回一個關於特定文件的ZipInfo 對象 example.txt爲壓縮文件中的某一文件
spamInfo.file_size 返回源文件大小 單位字節
spamInfo.compress_size 返回壓縮後文件大小 單位字節
exampleZip.extractall(path)) 解壓壓縮文件到path目錄 path不寫,默認爲當前目錄
exampleZip.extract(‘spam.txt’, path) 提取某一壓縮文件當path目錄 path不寫,默認爲當前目錄
newZip = zipfile.ZipFile(‘new.zip’, ‘w’) 以“寫模式”打開ZipFile 對象
newZip.write(‘spam.txt’, compress_type=zipfile.ZIP_DEFLATED) 壓縮文件 第一個參數是要添加的文件。第二個參數是“壓縮類型”參數
newZip.close() 關閉ZipFile對象

2. 項目練習

2.1 將帶有美國風格日期的文件改名爲歐洲風格日期

# 導入模塊
import shutil
import os
import re
# Renames filenames with American MM-DD-YYYY date format to European DD-MM-YYYY.

# 含美國風格的日期
# Create a regex that matches files with the American date format.
datePattern = re.compile(
    # 匹配文件名開始處、日期出現之前的任何文本
    r"""^(.*?) # all text before the date
        # 匹配月份
        ((0|1)?\d)- # one or two digits for the month
        # 匹配日期
        ((0|1|2|3)?\d)- # one or two digits for the day
        # 匹配年份
        ((19|20)\d\d) # four digits for the year
        (.*?)$ # all text after the date
        """, re.VERBOSE)

# 查找路徑
searchPath='d:/'

for amerFilename in os.listdir(searchPath):
    mo = datePattern.search(amerFilename)
    # Skip files without a date.
    if mo == None:
        continue
    # Get the different parts of the filename.
    # 識別日期
    beforePart = mo.group(1)
    monthPart = mo.group(2)
    dayPart = mo.group(4)
    yearPart = mo.group(6)
    afterPart = mo.group(8)

    # Form the European-style filename. 改爲歐洲式命名
    euroFilename = beforePart + dayPart + '-' + \
        monthPart + '-' + yearPart + afterPart
    # Get the full, absolute file paths.
    # 返回絕對路徑
    absWorkingDir = os.path.abspath(searchPath)
    # 原文件名
    amerFilename = os.path.join(absWorkingDir, amerFilename)
    # 改後文件名
    euroFilename = os.path.join(absWorkingDir, euroFilename)
    # Rename the files.
    print('Renaming "%s" to "%s"...' % (amerFilename, euroFilename))
    shutil.move(amerFilename, euroFilename)  # uncomment after testing
Renaming "d:\今天是06-28-2019.txt" to "d:\今天是28-06-2019.txt"...

2.2 將一個文件夾備份到一個ZIP 文件


import zipfile
import os


# 弄清楚ZIP 文件的名稱
def backupToZip(folder):
    # Backup the entire contents of "folder" into a ZIP file.
    # 獲得文件夾絕對路徑
    folder = os.path.abspath(folder)  # make sure folder is absolute
    # Figure out the filename this code should use based on
    # what files already exist.
    number = 1
    while True:
        # 壓縮文件名
        zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
        # 如果壓縮文件不存在
        if not os.path.exists(zipFilename):
            break
        number = number + 1

    # Create the ZIP file.
    print('Creating %s...' % (zipFilename))
    # 創建新ZIP 文件
    backupZip = zipfile.ZipFile(zipFilename, 'w')
    # TODO: Walk the entire folder tree and compress the files in each folder.
    print('Done.')

    # 提取文件目錄
    # 一層一層獲得目錄
    # Walk the entire folder tree and compress the files in each folder.
    for foldername, subfolders, filenames in os.walk(folder):
        print('Adding files in %s...' % (foldername))

        # 壓縮文件夾
        # Add the current folder to the ZIP file.
        backupZip.write(foldername)

        # Add all the files in this folder to the ZIP file.
        for filename in filenames:
            newBase = os.path.basename(folder) + '_'
            # 判斷文件是否是壓縮文件
            if filename.startswith(newBase) and filename.endswith('.zip'):
                continue  # don't backup the backup ZIP files
            backupZip.write(os.path.join(foldername, filename))
    backupZip.close()
    print('Done.')


backupToZip('image')
Creating image_1.zip...
Done.
Done.

2.3 選擇性拷貝

編寫一個程序,遍歷一個目錄樹,查找特定擴展名的文件(諸如.pdf 或.jpg)。不論這些文件的位置在哪裏,將它們拷貝到一個新的文件夾中。

import shutil
import os


def searchFile(path, savepath):
    # 判斷要保存的文件夾路徑是否存在
    if not os.path.exists(savepath):
        # 創建要保存的文件夾
        os.makedirs(savepath)
    # 遍歷文件夾
    for foldername, subfolders, filenames in os.walk(path):
        for filename in filenames:
            # 判斷是不是txt或者pdf文件
            if filename.endswith('txt') or filename.endswith('pdf'):
                inputFile = os.path.join(foldername, filename)
                # 保存文件路徑
                outputFile = os.path.join(savepath, filename)
                # 文件保存
                shutil.copy(inputFile, outputFile)


searchFile("mytest", "save")

2.4 刪除不需要的文件

編寫一個程序,遍歷一個目錄樹,查找特別大的文件或文件夾。將這些文件的絕對路徑打印到屏幕上。


import os


def deletefile(path):
    for foldername, subfolders, filenames in os.walk(path):
        for filename in filenames:
            # 絕對路徑
            filepath = os.path.join(foldername, filename)
            # 如果文件大於100MB
            if os.path.getsize(filepath)/1024/1024 > 100:
                # 獲得絕對路徑
                filepath = os.path.abspath(filepath)
                print(filepath)
                # 刪除文件
                os.unlink(filepath)


deletefile("mytest")

2.5 消除缺失的編號

編寫一個程序,在一個文件夾中,找到所有帶指定前綴的文件,諸如spam001.txt,spam002.txt 等,並定位缺失的編號(例如存在spam001.txt 和spam003.txt,但不存在spam002.txt)。讓該程序對所有後面的文件改名,消除缺失的編號。


import os
import re
# 路徑地址
path = '.'
fileList = []
numList = []
# 尋找文件
pattern = re.compile('spam(\d{3}).txt')
for file in os.listdir(path):
    mo = pattern.search(file)
    if mo != None:
        fileList.append(file)
        numList.append(mo.group(1))

# 對存儲的文件排序
fileList.sort()
numList.sort()

# 開始缺失的文件編號
# 編號從1開始
index = 1
# 打印不連續的文件
for i in range(len(numList)):
    # 如果文件編號不連續
    if int(numList[i]) != i+index:
        inputFile = os.path.join(path, fileList[i])
        print("the missing number file is {}:".format(inputFile))
        outputFile = os.path.join(path, 'spam'+'%03d' % (i+1)+'.txt')
        os.rename(inputFile, outputFile)
the missing number file is .\spam005.txt:
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章