2026/7/11 1:28:06

影刀RPA Python节点中操作文件系统:读写文件、遍历目录、压缩解压

影刀RPA Python节点中操作文件系统:读写文件、遍历目录、压缩解压 影刀RPA Python节点中操作文件系统读写文件、遍历目录、压缩解压影刀的文件操作动作覆盖了基本的创建/复制/删除/移动。但遇到复杂场景——递归遍历子目录、按文件大小筛选、批量重命名、压缩解压——就得靠Python节点了。这篇文章给出文件系统操作的标准代码片段每一段都能直接拷过去用。遍历目录列出所有文件含子目录importos folderrC:\RPA_data\reportsall_files[]forroot,dirs,filesinos.walk(folder):forfilenameinfiles:full_pathos.path.join(root,filename)all_files.append({path:full_path,![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/ab49f2de7506479185c019d71d639b73.png#pic_center)name:filename,folder:root,size:os.path.getsize(full_path),modified:os.path.getmtime(full_path),})print(f共找到{len(all_files)}个文件)只列出特定类型importosimportglob# 方法1glob模式匹配excel_filesglob.glob(rC:\RPA_data\**\*.xlsx,recursiveTrue)# 方法2手动过滤forroot,dirs,filesinos.walk(folder):forfinfiles:iff.endswith((.xlsx,.xls)):# 处理Excel文件pass按文件修改时间筛选拼多多店群自动化上架方案importosimporttime# 找最近24小时修改过的文件nowtime.time()recent_files[]![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/9f577daaa92c4524886017dd14996980.png#pic_center)forroot,dirs,filesinos.walk(folder):forfinfiles:pathos.path.join(root,f)ifnow-os.path.getmtime(path)86400:# 24小时 86400秒recent_files.append(path)文件读写文本文件# 读withopen(rC:\data\log.txt,r,encodingutf-8)asf:contentf.read()# 逐行读大文件withopen(rC:\data\log.txt,r,encodingutf-8)asf:forlineinf:print(line.strip())# 写覆盖withopen(rC:\data\output.txt,w,encodingutf-8)asf:f.write(第一行\n)f.write(第二行\n)# 追加withopen(rC:\data\log.txt,a,encodingutf-8)asf:f.write(新的一行\n)JSON文件importjson# 读withopen(rC:\data\config.json,r,encodingutf-8)asf:configjson.load(f)# 写data{name:张三,orders:[1,2,3]}withopen(rC:\data\output.json,w,encodingutf-8)asf:json.dump(data,f,ensure_asciiFalse,indent2)文件批量处理批量重命名importos folderrC:\RPA_data\imagesfori,filenameinenumerate(os.listdir(folder),1):iffilename.endswith(.png):old_pathos.path.join(folder,filename)new_namefproduct_{i:04d}.png# product_0001.pngnew_pathos.path.join(folder,new_name)os.rename(old_path,new_path)print(f{filename}→{new_name})批量移动文件按条件分类importosimportshutil sourcerC:\RPA_data\incomingdest_excelrC:\RPA_data\excel_filesdest_imagesrC:\RPA_data\imagesdest_othersrC:\RPA_data\othersos.makedirs(dest_excel,exist_okTrue)os.makedirs(dest_images,exist_okTrue)os.makedirs(dest_others,exist_okTrue)forfilenameinos.listdir(source):srcos.path.join(source,filename)ifnotos.path.isfile(src):continueiffilename.endswith((.xlsx,.xls)):shutil.move(src,os.path.join(dest_excel,filename))eliffilename.endswith((.png,.jpg,.jpeg)):shutil.move(src,os.path.join(dest_images,filename))else:shutil.move(src,os.path.join(dest_others,filename))压缩与解压压缩文件/文件夹importzipfileimportosdefzip_folder(folder_path,output_path):压缩整个文件夹withzipfile.ZipFile(output_path,w,zipfile.ZIP_DEFLATED)aszf:forroot,dirs,filesinos.walk(folder_path):forfileinfiles:file_pathos.path.join(root,file)arcnameos.path.relpath(file_path,folder_path)zf.write(file_path,arcname)print(f压缩完成{output_path})defzip_files(file_list,output_path):压缩指定文件列表withzipfile.ZipFile(output_path,w,zipfile.ZIP_DEFLATED)aszf:forfilepathinfile_list:zf.write(filepath,os.path.basename(filepath))print(f压缩完成{output_path}{len(file_list)}个文件)# 使用zip_folder(rC:\RPA_data\reports,rC:\RPA_data\reports_backup.zip)解压importzipfiledefunzip_file(zip_path,extract_to):解压zip文件withzipfile.ZipFile(zip_path,r)aszf:zf.extractall(extract_to)[video(video-GZQFjvBh-1783622761443)(type-csdn)(url-https://live.csdn.net/v/embed/524993)(image-https://v-blog.csdnimg.cn/asset/a547123d88ad712dccba346c9217e237/cover/Cover0.jpg)(title-TEMU店群如何管理运营)]# 列出解压的文件withzipfile.ZipFile(zip_path,r)aszf:print(f解压了{len(zf.namelist())}个文件到{extract_to})unzip_file(rC:\RPA_data\data.zip,rC:\RPA_data\extracted)文件夹操作importosimportshutil# 创建嵌套目录os.makedirs(rC:\RPA_data\2026\07\01,exist_okTrue)# 复制文件夹含所有内容shutil.copytree(rC:\RPA_data\source,rC:\RPA_data\backup)# 删除文件夹含所有内容shutil.rmtree(rC:\RPA_data\temp)![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/98f55d164ba7427aadc21857f233cad6.png#pic_center)# 获取文件夹大小defget_folder_size(folder):total0forroot,dirs,filesinos.walk(folder):forfinfiles:totalos.path.getsize(os.path.join(root,f))returntotal size_mbget_folder_size(rC:\RPA_data)/(1024*1024)print(f文件夹大小{size_mb:.2f}MB)文件清理安全版importosimporttimedefsafe_cleanup(folder,days_old30,dry_runTrue):清理N天之前的文件dry_runTrue只列不删nowtime.time()cutoffnow-days_old*86400to_delete[]forroot,dirs,filesinos.walk(folder):forfinfiles:pathos.path.join(root,f)ifos.path.getmtime(path)cutoff:to_delete.append(path)print(f将清理{len(to_delete)}个文件{days_old}天前)forpathinto_delete[:10]:# 只显示前10个print(f{path})ifnotdry_runandto_delete:print(f开始删除...)forpathinto_delete:try:os.remove(path)exceptExceptionase:print(f 删除失败{path}—{e})print(清理完成)# 先做一次dry_run看看要删什么safe_cleanup(rC:\RPA_data\temp,days_old7,dry_runTrue)# 确认OK后正式清理# safe_cleanup(rC:\RPA_data\temp, days_old7, dry_runFalse)dry_runTrue的安全机制是推荐的——先看一遍要删什么确认没删错再正式执行。总结文件系统操作在Python里就是os、shutil、zipfile三个模块的事。遍历用os.walk移动用shutil.move/copy压缩用zipfile。批量操作前先用dry_run模式预览避免删错。作者林焱