日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

10个关于文件操作的小功能(Python),都很实用~

發布時間:2025/3/8 python 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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_extnew_ext = args['new_ext'][0]if new_ext[0] != '.':new_ext = '.' + new_extbatch_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 osdef 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 lstr = find_file('.','md') print(r) # 返回所有目錄下的md文件

5 批量轉換xls文件為xlsx

#批量轉換文件xls-xlsx import win32com.client as win32 import os.path import osdef 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-modefiedTimeif 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 timedef 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_newsbatch_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 Counterseg = 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小抄非常適合在通勤路上用學習

往期精彩回顧2019年公眾號文章精選適合初學者入門人工智能的路線及資料下載機器學習在線手冊深度學習在線手冊AI基礎下載(第一部分)備注:加入本站微信群或者qq群,請回復“加群”加入知識星球(4600+用戶,ID:92416895),請回復“知識星球”

喜歡文章,點個在看

與50位技術專家面對面20年技術見證,附贈技術全景圖

總結

以上是生活随笔為你收集整理的10个关于文件操作的小功能(Python),都很实用~的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。