【发布时间】:2012-09-26 15:32:17
【问题描述】:
我有多个看起来像 folder.0 和 folder.1 的文件夹。
在每个文件夹中都有一个文件 ('junk'),我想将其复制并重命名为当前所在文件夹名称的 .0 或 .1 部分。
这是我想要做的:
inDirec = '/foobar'
outDirec = '/complete/foobar'
for root, dirs,files in os.walk(inDirec):
for file in files:
if file =='junk'
d = os.path.split(root)[1]
filename, iterator = os.path.splitext(d) # folder no. captured
os.rename(file, iterator+file) # change name to include folder no.
fullpath = os.path.join(root,file)
shutil.copy(fullpath,outDirec)
这会返回:
os.rename(file,iterator+file)
OSError: [Errno 2] No such file or directory
我什至不确定我应该使用 os.rename。我只想提取files == 'junk' 并将它们复制到一个目录,但它们都具有完全相同的名称。所以我真的只需要重命名它们,这样它们就可以存在于同一个目录中。有什么帮助吗?
更新
for root, dirs,files in os.walk(inDirec):
for file in files:
if file =='junk'
d = os.path.split(root)[1]
filename, iterator = os.path.splitext(d) # folder no. captured
it = iterator[-1] # iterator began with a '.'
shutil.copy(os.path.join(root,file),os.path.join(outDirec,it+file))
【问题讨论】:
标签: python operating-system rename