enumerate Files and Folders(遍历)

本文详细探讨了iOS开发过程中的关键技术和优化策略,包括Objective-C和Swift编程语言的应用,Xcode开发环境的高效利用,以及如何实现流畅的用户体验。同时,介绍了iOS应用的性能优化、安全性考量及发布流程,旨在帮助开发者构建高质量的移动应用。

1。对指定目录的浅遍历

   - (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error 

e.g.

- (void) actionEnumerate{ 

    NSFileManager *fileManager = [[NSFileManager alloc] init];

    NSString *bundleDir = [[NSBundle mainBundle] bundlePath];

    NSError *error = nil;

    NSArray *bundleContents = [fileManager  contentsOfDirectoryAtPath:bundleDir  error:&error];  

    if ([bundleContents count] > 0 && error == nil){

        NSLog(@"Contents of the app bundle = %@", bundleContents);

    }

    else if ([bundleContents count] == 0 && error == nil){

        NSLog(@"Call the police! The app bundle is empty.");

    }

    else {

        NSLog(@"An error happened = %@", error);

    }

}

2。对指定目录的浅遍历(并能获取到结果中每一数据项的额外信息,如是否文件,创建时间等)

   - (NSArray *)contentsOfDirectoryAtURL:(NSURL *)url includingPropertiesForKeys:(NSArray *)keys

                             options:(NSDirectoryEnumerationOptions)mask error:(NSError **)error 

参数

   includingPropertiesForKeys: NSURLIsDirectoryKey / NSURLIsReadableKey / NSURLCreationDateKey

                               NSURLContentAccessDateKey / NSURLContentModificationDateKey

   options:0 //显示全部文件

           NSDirectoryEnumerationSkipsHiddenFiles //忽略隐藏文件

3。获取文件属性 (NSURL类的实例方法)

   - (BOOL)getResourceValue:(out id *)value forKey:(NSString *)propertyKey error:(out NSError **)error


e.g.

//获取指定文件夹(.app)下的内容(返回结果中的每一项都是NSURL,且带有各种属性,如创建日期,最后修改日期等)

- (NSArray *) contentsOfAppBundle{

    NSFileManager *manager = [[NSFileManager alloc] init];

    NSURL *bundleDir = [[NSBundle mainBundle] bundleURL];

    //各种属性

    NSArray *propertiesToGet = @[

                                NSURLIsDirectoryKey,

                                 NSURLIsReadableKey,

                                 NSURLCreationDateKey,

                                 NSURLContentAccessDateKey,

                                 NSURLContentModificationDateKey

                                 ];


    NSError *error = nil;

    NSArray *result = [manager contentsOfDirectoryAtURL:bundleDir includingPropertiesForKeys:propertiesToGet

                                                options:0  error:&error];    

    if (error != nil){

        NSLog(@"An error happened = %@", error);

    }    

    return result;

}


- (NSString *) stringValueOfBoolProperty:(NSString *)paramProperty  ofURL:(NSURL *)paramURL{

    NSNumber *boolValue = nil;

    NSError *error = nil;

    [paramURL getResourceValue:&boolValue forKey:paramProperty  error:&error];

    if (error != nil){

        NSLog(@"Failed to get property of URL. Error = %@", error);

    }

    return [boolValue isEqualToNumber:@YES] ? @"Yes" : @"No";   

}

- (NSString *) isURLDirectory:(NSURL *)paramURL{

    return [self stringValueOfBoolProperty:NSURLIsDirectoryKey ofURL:paramURL];

}

- (NSString *) isURLReadable:(NSURL *)paramURL{

    return [self stringValueOfBoolProperty:NSURLIsReadableKey ofURL:paramURL];

}


- (NSDate *) dateOfType:(NSString *)paramType inURL:(NSURL *)paramURL{

    NSDate *result = nil;

    NSError *error = nil;

   [paramURL getResourceValue:&result forKey:paramType  error:&error];

    if (error != nil){

        NSLog(@"Failed to get property of URL. Error = %@", error);

    }

    return result;

}


- (void) printURLProperties:(NSURL *)paramURL{    

    NSLog(@"Item name = %@", [paramURL lastPathComponent]);

    NSLog(@"Is a Directory? %@", [self isURLDirectory:paramURL]);

    NSLog(@"Is Readable? %@", [self isURLReadable:paramURL]);

    NSLog(@"Creation Date = %@",

          [self dateOfType:NSURLCreationDateKey inURL:paramURL]);

    NSLog(@"Access Date = %@",

          [self dateOfType:NSURLContentAccessDateKey inURL:paramURL]);

    NSLog(@"Modification Date = %@",

          [self dateOfType:NSURLContentModificationDateKey inURL:paramURL]);

}


-(void)actionEnumerate {

    NSArray *itemsInAppBundle = [self contentsOfAppBundle];

    for (NSURL *item in itemsInAppBundle){

        [self printURLProperties:item];

    }

}


postscript: 
    1。上述罗列的方法是属于浅遍历,若要深入遍历则需用

       enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:


from playwright.sync_api import sync_playwright import subprocess import time import os debugging_ports = [9222, 9223, 9224, 9225] chrome_path = "C:\\Users\\Windows10\\Desktop\\chromedriver-win64\\chrome-win64\\chrome.exe" subprocess.Popen([ chrome_path, f"--remote-debugging-port={debugging_ports[0]}", "https://www.dianxiaomi.com/web/popTemu/add" ]) all_files = [] # 存储所有要上传的文件路径 root_folder = "C:\\Users\\Windows10\\Desktop\\素材" # 替换为需要上传文件夹的路径 dz_numbered_folders = [ folder for folder in os.listdir(root_folder) if folder.startswith("DZ") and folder[2:].isdigit() and os.path.isdir(os.path.join(root_folder, folder)) ] print(f"找到 {len(dz_numbered_folders)} 个 DZ+数字 的文件夹:") dz_numbered_folders.sort()# 排序确保按 DZ001 -> DZ002 顺序上传 def upload_folder(folder_name, port): folder_path = os.path.join(root_folder, folder_name) process = subprocess.Popen([ chrome_path, f"--remote-debugging-port={port}", "https://www.dianxiaomi.com/web/popTemu/add" ])# 启动 Chrome 并打开目标网页 time.sleep(2) # 等待浏览器启动 with sync_playwright() as p: try: browser = p.chromium.connect_over_cdp(f"http://localhost:{port}") page = browser.contexts[0].pages[0] # 获取第一个上下文的第一个页面 # 定位按钮并悬停 button = page.locator("button:has-text('选择图片')") button.hover() print("鼠标已悬停在按钮上") # 定位并点击“本地图片”选项 page.wait_for_selector("li[data-menu-id='local']", timeout=1000) page.locator("li[data-menu-id='local']").click() print("已点击“本地图片”选项") files_in_folder = [ os.path.join(folder_path, f) for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f)) and f.lower().endswith(('.png', '.jpg', '.jpeg')) ] if files_in_folder: print(f"准备上传 {len(files_in_folder)} 个文件...") page.set_input_files("input[type=file]", files_in_folder)# 批量上传文件(页面中有一个隐藏的 <input type="file"> 元素) print("文件上传完成!") else: print(f"文件夹 {folder_name} 中没有图片可上传。") print("请关闭浏览器窗口以继续下一个文件夹...") while True: if not browser.contexts or not browser.contexts[0].pages: print("页面已关闭,继续下一个任务。") break time.sleep(1) browser.close()# 关闭浏览器连接 # # 遍历每个 DZ 文件夹 # for folder in dz_numbered_folders: # full_folder_path = os.path.join(root_folder, folder) # 修复:加上 root_folder # print(f"正在处理文件夹:{folder}") # # files_in_folder = [ # # os.path.join(folder, f) for f in os.listdir(folder) # # if os.path.isfile(os.path.join(folder, f)) and f.lower().endswith(('.png', '.jpg', '.jpeg')) # # ] # file_paths = [ # os.path.join(root_folder, f) for f in os.listdir(root_folder) # if os.path.isfile(os.path.join(root_folder, f)) and f.lower().endswith(('.png', '.jpg', '.jpeg')) # ] # all_files.extend(file_paths) # # 批量上传文件(页面中有一个隐藏的 <input type="file"> 元素) # if all_files: # print(f"准备上传 {len(all_files)} 个文件...") # page.set_input_files("input[type=file]", all_files) # print("所有文件上传完成!") # else: # print("没有找到任何可上传的文件。") except Exception as e: print(f"操作失败:{e}") finally: process.terminate() # 关闭浏览器进程 for i, folder in enumerate(dz_numbered_folders): upload_folder(folder, debugging_ports[i % len(debugging_ports)]) 代码如上,打开是多个标签页,我需要打开多个窗口,如何修改
09-11
def backup_excel_files(self, folder_path, backup_dir): """递归查找并备份所有Sound_Pres_Cal.xlsx文件""" self.log(f"开始在文件夹中搜索Sound_Pres_Cal.xlsx: {folder_path}") backup_count = 0 # 使用os.walk递归遍历所有子文件夹 for root, dirs, files in os.walk(folder_path): # 使用folder_path参数 for file in files: if file == "Sound_Pres_Cal.xlsx": excel_path = os.path.join(root, file) try: # 计算相对路径以保持目录结构 rel_path = os.path.relpath(excel_path, start=folder_path) dest_path = os.path.join(backup_dir, rel_path) # 创建目标目录结构 os.makedirs(os.path.dirname(dest_path), exist_ok=True) # 复制文件(保留元数据) shutil.copy2(excel_path, dest_path) backup_count += 1 self.log(f"备份成功: {excel_path} → {dest_path}") except Exception as e: self.log(f"备份失败 {excel_path}: {str(e)}") self.log(f"共找到并备份 {backup_count} 个Sound_Pres_Cal.xlsx文件") def process_folders(self): """处理多个文件夹中的Word文件""" try: # 提前初始化 output_folder(修复点1) if self.output_path: output_folder = self.output_path else: output_folder = next((p for p in self.folders if os.path.isdir(p)), os.getcwd()) self.log(f"开始处理 {len(self.folders)} 个文件夹...") # 获取所有文件夹中的Word文件 word_files = self.get_all_word_files(self.folders) if not word_files: self.log("没有找到任何Word文档") return self.log(f"共找到 {len(word_files)} 个Word文档") self.progress["maximum"] = len(word_files) + 5 # 文件数 + 合并步骤 backup_dir = os.path.join(output_folder, "原始Word备份") if self.backup_mode.get(): os.makedirs(backup_dir, exist_ok=True) # 创建临时目录存储转换后的PDF with tempfile.TemporaryDirectory() as temp_dir: pdf_files_with_header = [] toc_entries = [] all_tables = {} current_page = 1 # 处理每个Word文件 for i, word_file in enumerate(word_files): self.progress["value"] = i + 1 # 修改点:只获取文件名,不包含路径 file_name = os.path.splitext(os.path.basename(word_file))[0] display_name = file_name # 这里只使用文件名 original_pdf = os.path.join(temp_dir, f"{file_name}_original.pdf") pdf_with_header = os.path.join(temp_dir, f"{file_name}_with_header.pdf") if self.backup_mode.get(): try: # 优化路径处理逻辑 dest_dir = os.path.join(backup_dir, os.path.basename(os.path.dirname(word_file))) os.makedirs(dest_dir, exist_ok=True) # 确保目标目录存在 # 直接复制文件 self.backup_excel_files(folder_path, backup_dir) dest_path = os.path.join(dest_dir, os.path.basename(word_file)) shutil.copy2(word_file, dest_path) except OSError as e: print(f"文件备份失败: {e}") # 可添加日志记录或错误处理回调 except Exception as e: print(f"未知错误: {e}") self.backup_excel_files(folder_path, backup_dir)这句代码报错是什么原因
最新发布
09-14
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值