![](/img/trans.png)
[英]How can I use Python to walk through files in directories and output a pandas data frame given certain constraints?
[英]How to simply walk through directories and subdirectories and create archive if found certain files
我想創建 2 個腳本。 首先負責遍歷父文件夾中的所有子目錄,查找擴展名為"*.mp4", "*.txt","*.jpg"
文件,如果找到包含這三個文件的文件夾(例如testfolder
),另一個腳本執行創建存檔testfolder.tar
操作。
這是我用於測試這些腳本的目錄樹: https : //imgur.com/4cX5t5N
rootDirectory
包含parentDirectory1
和parentDirectory2
。 parentDirectories
包含childDirectories
。
這是dirScanner.py
嘗試打印子目錄中文件擴展名的代碼:
import os
rootdir = r'C:\Users\user\pythonprogram\rootDirectory'
for directory in os.walk(rootdir):
for subdirectory in directory:
extensions = []
if os.path.isfile(os.curdir):
extensions.append(os.path.splitext(os.curdir)[-1].lower())
print(extensions)
然而,它絕對不能像我期望的那樣工作。 我應該如何遍歷rootDirectory
parentDirectories
和childDirectiories
?
我想保持簡單,以“好吧我在這個目錄中,這個目錄的文件是XXX,應該/不應該打包它們”的方式
此外,這是我的另一個腳本,應該負責為指定路徑打包文件。 我正在嘗試學習如何使用類,但我不知道我是否理解正確。
import tarfile
class folderNeededToBePacked:
def __init__(self, name, path):
self.path = path
self.name = name
def pack(self):
tar = tarfile.open(r"{0}/{1}.tar".format(self.path, self.name), "w")
for file in self.path:
tar.add(file)
tar.close()
我將感謝所有關於如何實現此任務目標的提示和建議。
這是一個簡單直接的任務,沒有很多復雜的概念,需要作為一個類來實現,所以我不會為此使用一個。
這個想法是遍歷所有目錄(遞歸),如果找到匹配的目錄,則將該目錄的三個文件打包到存檔中。
要遍歷目錄樹,您需要根據其文檔修復“os.walk()”的用法:
tar = tarfile.open(...)
for dirpath, dirnames, filenames in os.walk(root):
found_files = dir_matching(root, dirpath)
for found_file in found_files:
tar.add(found_file)
tar.close()
並且函數dir_matching()
應該返回三個找到的文件的列表(如果目錄不匹配,則返回一個空列表,即至少缺少三個必要文件之一):
def dir_matching(root, dirpath):
jpg = glob.glob(os.path.join(root, dirpath, '*.jpg')
mp4 = glob.glob(os.path.join(root, dirpath, '*.mp4')
txt = glob.glob(os.path.join(root, dirpath, '*.txt')
if jpg and mp4 and txt:
return [ jpg[0], mp4[0], txt[0] ]
else:
return []
當然,您可以添加更復雜的檢查,例如是否僅找到一個 jpg 等,但這取決於您的具體規格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.