今天项目经理叫我写一个python脚本,但是我从没写过脚本文件,求大神门帮忙

如题,需求如下:


假如在D盘下的TEST文件夹中传了一个AAAA_BBBB_CCCC_DDD.txt的文件,就将这个文件名称拆分,建一个AAAA的目录,在AAAA的目录中建BBBB的子目录,在BBBB的子目录中建CCCC的子目录,最后将DDD.txt存放到CCCC子目录中。

大概就是这样的一个需求

文件名称可能不是固定不变的,可能是动态的。


求各位python大神能帮忙给个思路啊,谢谢了!


largeQ
浏览 326回答 3
3回答

动漫人物

PHP实现(思路):<?php chdir('/home/eechen/TEST'); $path&nbsp;=&nbsp;pathinfo('/home/eechen/TEST/AA_BB_CC_DD.txt'); $arr&nbsp;=&nbsp;explode('_',$path['filename']); $count&nbsp;=&nbsp;count($arr); foreach($arr&nbsp;as&nbsp;$k&nbsp;=>&nbsp;$v)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if($k!=$count-1)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(!file_exists($v))&nbsp;{ mkdir($v); chdir($v); echo&nbsp;getcwd()."\n"; }&nbsp;else&nbsp;{ chdir($v); } }&nbsp;else&nbsp;{ $file&nbsp;=&nbsp;$v.'.'.$path['extension']; if(!file_exists($file))&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;touch($file); &nbsp;&nbsp;&nbsp;&nbsp;echo&nbsp;getcwd().'/'.$file."\n"; } } }

智慧大石

import osimport shutildir="C:\\Users\\Lenovo\\Desktop\\figure-it\\学习\\python";fileNames = os.listdir(dir);if(len(fileNames)>0):&nbsp;for fn in fileNames:&nbsp;&nbsp;if(fn.find("_") != -1):&nbsp;&nbsp;&nbsp;n = fn[0:len(fn)-4];&nbsp;&nbsp;&nbsp;names = n.split('_');&nbsp;&nbsp;&nbsp;last = names[-1];&nbsp;&nbsp;&nbsp;suffix = fn[len(fn)-4:len(fn)];&nbsp;&nbsp;&nbsp;path = "";&nbsp;&nbsp;&nbsp;for name in names:&nbsp;&nbsp;&nbsp;&nbsp;path = os.path.join(path,name);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fullpath = os.path.join(dir,path);&nbsp;&nbsp;&nbsp;if not os.path.exists(fullpath):&nbsp;&nbsp;&nbsp;&nbsp;os.makedirs(fullpath);&nbsp;&nbsp;&nbsp;shutil.copy(os.path.join(dir,fn),fullpath);&nbsp;&nbsp;&nbsp;os.remove(os.path.join(dir,fn));&nbsp;&nbsp;&nbsp;os.rename(os.path.join(fullpath,fn),os.path.join(fullpath,last+suffix));
打开App,查看更多内容
随时随地看视频慕课网APP