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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

Python实现目录文件扫描功能

發布時間:2023/12/15 综合教程 25 生活家
生活随笔 收集整理的這篇文章主要介紹了 Python实现目录文件扫描功能 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

日常程序編寫中常常遇到需要獲取目錄下文件的功能,對該功能做個簡單整理,供大家參考。

實現遍歷目錄文件最常用的方法是os.listdir(),還有一種os.walk方法。
一、os.listdir方法

源碼中對該方法的描述“Return a list containing the names of the files in the directory.” 入參為目錄,返回目錄下的所有文件名,以列表的形式。返回的列表是無序的,但是不包括特殊條目“.”、“..” , 即使它們在目錄中是存在的。

語法格式如下:

os.listdir(path)

舉個栗子:

1 def get_dirnames(filePath):
2     lists = os.listdir(filePath)
3     # 打印獲取files name列表信息
4     print(lists)
5 # 調用方法,傳入指定目錄
6 get_dirnames("D:Python_locationDemo03ddt_demo")

執行結果:

返回列表信息['10.txt', '121212.txt', '1232323.py', '21.txt', '2121.py', 'ddt_test.py', 'send_email.py', '__init__.py']是無序的。

通過listdir得到的僅是當前路徑下的文件名,不包括子目錄中的文件,如果需要得到所有文件可以使用遞歸方法。可參考如下demo:

 1 def get_dirnames(filePath):
 2     print("
 ************ listdir demo ************")
 3     print("current dir : {0}".format(filePath))
 4     lists = os.listdir(filePath)
 5     # 打印獲取files name列表信息
 6     print(lists)
 7     for cur_file in lists:
 8         # 遍歷出lists內的文件名并拼接filePath,使得到一個新的路徑或者文件絕對路徑
 9         path = os.path.join(filePath, cur_file)
10         # 判斷新的路徑是否是文件:是文件則不需要繼續查看,是目錄則需要繼續遍歷該目錄下的文件名
11         # if os.path.isfile(path): 
12             # print("{0} is file!".format(cur_file))
13         if os.path.isdir(path):
14             # print("{0} is dir!".format(cur_file))
15             # 如果是目錄,繼續遞歸該目錄,重復調用get_dirnames方法遞歸目錄
16             get_dirnames(path) 
17 # 調用方法,傳入指定目錄
18 get_dirnames("D:Python_locationDemo03ddt_demo")

實際目錄:

運行結果:

逐個目錄輸出目錄下的所有文件信息。能夠得到所有文件名,但是引用不方便,以下代碼可供參考。

 1 import os
 2 def new_report(testreport):
 3     """
 4     生成最新的測試報告文件
 5     :param testreport:
 6     :return:返回文件
 7     """
 8     lists = os.listdir(testreport)
 9     lists.sort(key=lambda fn: os.path.getmtime(testreport + "\" + fn))
10     file_new = os.path.join(testreport, lists[-1])
11     return file_new

1、讀取指定目錄下的所有文件名

2、排序(項目中是按照時間順序排列)后取最新的文件

3、返回值(最新文件全名)

二、os.walk方法

os.walk()方法用于通過在目錄樹中游走輸出在目錄中的文件名,向上或者向下。是一個簡單易用的文件、目錄遍歷器,可以幫助我們高效的處理文件、目錄方面的事情。

語法格式如下:

os.walk(top, topdown=True, onerror=None, followlinks=False)

方法參數說明:

top:要遍歷的目錄的路徑
topdown:可選,如果為 True,則優先遍歷 top 目錄,以及 top 目錄下的每一個子目錄,否則優先遍歷 top 的子目錄,默認為 True
onerror: 可選, 需要一個 callable 對象,當 walk 異常時調用
followlinks:可選, 如果為 True,則會遍歷目錄下的快捷方式(linux 下是 symbolic link)實際所指的目錄,默認為 False
args:包含那些沒有 ‘-‘ 或 ‘—‘ 的參數列表

返回值: 三元組 (dirpath, dirnames, filenames)

dirpath:所指的是當前正在遍歷的目錄的地址
dirnames:當前文件夾中所有目錄名字的 list (不包括子目錄)
filenames:當前文件夾中所有的文件 (不包括子目錄中的文件)

 1 import os
 2 def get_file_name(filePath):
 3     ab = os.walk(filePath)
 4     for i, j, k in ab:
 5         print("*********打印i的內容*************")
 6         print(i)
 7         print("*********打印j的內容*************")
 8         print(j)
 9         print("*********打印k的內容*************")
10         print(k)
11 get_file_name("D:Python_locationDemo03ddt_demodsldls")

目錄結構:

運行結果:

三、其他跟文件相關的常用方法

os.path.splitext()分離文件名和文件擴展名

file = "test.txt"
file_name = os.path.splitext(file)[0]
file_suffix = os.path.splitext(file)[1]

# 執行結果,file_name: text file_suffix: .txt

os.path.exists:判斷文件或目錄是否存在

os.path.isfile():判斷是否是文件

os.path.isdir():判斷是否是目錄

os.path.dirname():獲取當前文件所在的目錄,即父目錄

"""該方法常用于獲取當前文件的目錄,并以此獲取根目錄,作為base directory,拼接路徑獲取文件"""
# 獲取當前文件所在目錄
os.path.dirname(__file__)
# 獲取當前文件所在目錄的上級目錄(一般框架中為項目根目錄)
os.path.dirname(os.path.dirname(__file__))

os.makedirs():創建多級目錄

os.makedir():創建單級目錄

os.path.getsize():獲取文件大小

以上內容為本次分享的主要內容,希望對大家工作學習中能有所幫助!感謝!

總結

以上是生活随笔為你收集整理的Python实现目录文件扫描功能的全部內容,希望文章能夠幫你解決所遇到的問題。

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