天天看點

10個關于檔案操作的小功能(Python),都很實用~

1 優雅的擷取檔案字尾名

import os
file_ext = os.path.splitext('./data/py/test.py')
front,ext = file_ext
In [5]: front
Out[5]: './data/py/test'

In [6]: ext
Out[6]: '.py'      

2 批量修改檔案字尾

本例子使用Python的​

​os​

​​子產品和 ​

​argparse​

​​子產品,将工作目錄​

​work_dir​

​​下所有字尾名為​

​old_ext​

​​的檔案修改為字尾名為​

​new_ext​

通過本例子,大家将會大概清楚​

​argparse​

​子產品的主要用法。

導入子產品

import argparse
import os      

定義腳本參數

def get_parser():
    parser = argparse.ArgumentParser(
        description='工作目錄中檔案字尾名修改')
    parser.add_argument('work_dir', metavar='WORK_DIR', type=str, nargs=1,
                        help='修改字尾名的檔案目錄')
    parser.add_argument('old_ext', metavar='OLD_EXT',
                        type=str, nargs=1, help='原來的字尾')
    parser.add_argument('new_ext', metavar='NEW_EXT',
                        type=str, nargs=1, help='新的字尾')
    return parser      

字尾名批量修改

def batch_rename(work_dir, old_ext, new_ext):
    """
    傳遞目前目錄,原來字尾名,新的字尾名後,批量重命名字尾
    """
    for filename in os.listdir(work_dir):
        # 擷取得到檔案字尾
        split_file = os.path.splitext(filename)
        file_ext = split_file[1]
        # 定位字尾名為old_ext 的檔案
        if old_ext == file_ext:
            # 修改後檔案的完整名稱
            newfile = split_file[0] + new_ext
            # 實作重命名操作
            os.rename(
                os.path.join(work_dir, filename),
                os.path.join(work_dir, newfile)
            )
    print("完成重命名")
    print(os.listdir(work_dir))      

實作Main

def main():
    """
    main函數
    """
    # 指令行參數
    parser = get_parser()
    args = vars(parser.parse_args())
    # 從指令行參數中依次解析出參數
    work_dir = args['work_dir'][0]
    old_ext = args['old_ext'][0]
    if old_ext[0] != '.':
        old_ext = '.' + old_ext
    new_ext = args['new_ext'][0]
    if new_ext[0] != '.':
        new_ext = '.' + new_ext

    batch_rename(work_dir, old_ext, new_ext)      

3 從路徑中提取檔案

In [11]: import os
    ...: file_ext = os.path.split('./data/py/test.py')
    ...: ipath,ifile = file_ext
    ...:

In [12]: ipath
Out[12]: './data/py'

In [13]: ifile
Out[13]: 'test.py'      

4 查找指定字尾名的檔案

import os

def find_file(work_dir,extension='jpg'):
    lst = []
    for filename in os.listdir(work_dir):
        print(filename)
        splits = os.path.splitext(filename)
        ext = splits[1] # 拿到擴充名
        if ext == '.'+extension:
            lst.append(filename)
    return lst

r = find_file('.','md')
print(r) # 傳回所有目錄下的md檔案      

5 批量轉換xls檔案為xlsx

#批量轉換檔案xls-xlsx
import win32com.client as win32
import os.path
import os


def xls2xlsx():    
    rootdir = r"C:\Users\CQ375\Desktop\temp1" #需要轉換的xls檔案存放處
    rootdir1 = r"C:\Users\CQ375\Desktop\ex" #轉換好的xlsx檔案存放處
    files = os.listdir(rootdir) #列出xls檔案夾下的所有檔案
    num = len(files) #列出所有檔案的個數
    for i in range(num): #按檔案個數執行次數
        kname = os.path.splitext(files[i])[1] #分離檔案名與擴充名,傳回(f_name, f_extension)元組
        if kname == '.xls': #判定擴充名是否為xls,屏蔽其它檔案
            fname = rootdir + '\\' + files[i] #合成需要轉換的路徑與檔案名
            fname1 = rootdir1 + '\\' + files[i] #合成準備存放轉換好的路徑與檔案名
            excel = win32.gencache.EnsureDispatch('Excel.Application') #調用win32子產品
            wb = excel.Workbooks.Open(fname) #打開需要轉換的檔案
            wb.SaveAs(fname1+"x", FileFormat=51) #檔案另存為xlsx擴充名的檔案
            wb.Close()
            excel.Application.Quit()
            
            
if __name__ == '__main__':
    xls2xlsx()      

6 目錄下所有檔案的修改時間

import os
import datetime
print(f"目前時間:{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
for root,dirs,files in os.walk(r"D:\works"):#循環D:\works目錄和子目錄
    for file in files:
        absPathFile=os.path.join(root,file)
        modefiedTime=datetime.datetime.fromtimestamp(os.path.getmtime(absPathFile))
        now=datetime.datetime.now()
        diffTime=now-modefiedTime
        if diffTime.days<20:#條件篩選超過指定時間的檔案
            print(f"{absPathFile:<27s}修改時間[{modefiedTime.strftime('%Y-%m-%d %H:%M:%S')}]\
距今[{diffTime.days:3d}天{diffTime.seconds//3600:2d}時{diffTime.seconds%3600//60:2d}]")#列印相關資訊      

7 批量壓縮檔案夾和檔案

import zipfile  # 導入zipfile,這個是用來做壓縮和解壓的Python子產品;
import os
import time

def batch_zip(start_dir):
    start_dir = start_dir  # 要壓縮的檔案夾路徑
    file_news = start_dir + '.zip'  # 壓縮後檔案夾的名字

    z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)
    for dir_path, dir_names, file_names in os.walk(start_dir):
        # 這一句很重要,不replace的話,就從根目錄開始複制
        f_path = dir_path.replace(start_dir, '')
        f_path = f_path and f_path + os.sep  # 實作目前檔案夾以及包含的所有檔案的壓縮
        for filename in file_names:
            z.write(os.path.join(dir_path, filename), f_path + filename)
    z.close()
    return file_news


batch_zip('./data/ziptest')      

8 檔案讀操作

import os
# 建立檔案夾

def mkdir(path):
    isexists = os.path.exists(path)
    if not isexists:
        os.mkdir(path)
# 讀取檔案資訊

def openfile(filename):
    f = open(filename)
    fllist = f.read()
    f.close()
    return fllist  # 傳回讀取内容      

9 檔案寫操作

# 寫入檔案資訊
# example1
# w寫入,如果檔案存在,則清空内容後寫入,不存在則建立
f = open(r"./data/test.txt", "w", encoding="utf-8")
print(f.write("測試檔案寫入"))
f.close

# example2
# a寫入,檔案存在,則在檔案内容後追加寫入,不存在則建立
f = open(r"./data/test.txt", "a", encoding="utf-8")
print(f.write("測試檔案寫入"))
f.close

# example3
# with關鍵字系統會自動關閉檔案和處理異常
with open(r"./data/test.txt", "w") as f:
    f.write("hello world!")      

10 分詞并儲存檔案

​pkuseg​

​​是北大開源的一個中文分詞工具包,它在多個分詞資料集上都有非常高的分詞準确率,比經常使用的​

​jieba​

​分詞性能和效果要更好。

下面使用​

​pkuseg​

​​的​

​cut​

​​函數,分詞後統計前10頻率詞,并按照所有詞的頻次由高到低寫入到檔案​

​cut_words.csv​

​ 中。

這是需要切分的段落:

mystr = """Python 語言參考 描述了 Python 語言的具體文法和語義,
這份庫參考則介紹了與 Python 一同發行的标準庫。
它還描述了通常包含在 Python 發行版中的一些可選元件。
Python 标準庫非常龐大,所提供的元件涉及範圍十分廣泛,
正如以下内容目錄所顯示的。這個庫包含了多個内置子產品 (以 C 編寫),
Python 程式員必須依靠它們來實作系統級功能,
例如檔案 I/O,此外還有大量以 Python 編寫的子產品,
提供了日常程式設計中許多問題的标準解決方案。
其中有些子產品經過專門設計,
通過将特定平台功能抽象化為平台中立的 API 來鼓勵和加強 Python 程式的可移植性。
Windows 版本的 Python 安裝程式通常包含整個标準庫,
往往還包含許多額外元件。對于類 Unix 作業系統,
Python 通常會分成一系列的軟體包,
是以可能需要使用作業系統所提供的包管理工具來擷取部分或全部可選元件。"""      

幾行代碼就完成上述工作:

from pkuseg import pkuseg
from collections import Counter

seg = pkuseg()
words = seg.cut(mystr)
frequency_sort = Counter(words).most_common()
with open('./data/cut_words.csv', 'w') as f:
    for line in frequency_sort:
        f.write(str(line[0])+',' + str(line[1])+"\n")

print('writing done')      

出現最高頻的前10個詞語:

Counter(words).most_common(10)
# [('的', 12), (',', 11), ('Python', 10), ('。', 7), ('了', 5), ('包含', 4), ('元件', 4), ('标準庫', 3), ('通常', 3), ('所', 3)]      

備注:公衆号菜單包含了整理了一本AI小抄,非常适合在通勤路上用學習。