Python:使用子目录重命名目录
我已经阅读了其他一些帖子,并尝试了这些答案中的代码,但无法让我的工作 这是我的文件结构:Python:使用子目录重命名目录,python,rename,Python,Rename,我已经阅读了其他一些帖子,并尝试了这些答案中的代码,但无法让我的工作 这是我的文件结构: motherfile g934uth98t motherfile g934uth98t/kid file fh984bvt34ynt motherfile g934uth98t/kid file fh984bvt34ynt/something elsee goes here 98573v4985hy4 motherfile g934uth98t/big bad wolf r6b5n656n 目标是: mo
motherfile g934uth98t
motherfile g934uth98t/kid file fh984bvt34ynt
motherfile g934uth98t/kid file fh984bvt34ynt/something elsee goes here 98573v4985hy4
motherfile g934uth98t/big bad wolf r6b5n656n
目标是:
motherfile
motherfile/kid file
motherfile/kid file/something elsee goes here
motherfile/big bad wolf
这是我的代码:
for root, dirs, files in os.walk(".", topdown=True):
for name in dirs:
direc = os.path.join(root, name)
newdirec = '.'
for part in direc.split('\\')[1:]:
newdirec += '\\'
newdirec += ' '.join(part.split()[:-1])
os.rename(direc,newdirec)
没有os.rename,并且使用prints(direc然后newdirec),它可以正常工作
motherfile g934uth98t
motherfile
motherfile g934uth98t/kid file fh984bvt34ynt
motherfile/kid file
motherfile g934uth98t/kid file fh984bvt34ynt/something elsee goes here 98573v4985hy4
motherfile/kid file/something elsee goes here
motherfile g934uth98t/big bad wolf r6b5n656n
motherfile/big bad wolf
但是,当它重命名时,它会删除母文件,但是所有其他目录都不再存在(因为它们是相对于母文件g934uth98t的),因此脚本结束
使用top-down=False
,我得到一个错误:
FileNotFoundError:[WinError 3]系统找不到指定的路径:'.\\motherfile g934uth98t\\kid file fh984bvt34ynt\\this elsee here 98573v4985hy4'->'.\\motherfile\\kid file\\this elsee here'
我怎样才能解决这个问题
编辑:
尝试了这个,仍然没有运气,同样的错误(第二个)。可能是Windows文件目录格式问题
import os
originaldirs = []
count = 0
def collect():
global originaldirs
originaldirs = []
for root, dirs, files in os.walk(".", topdown=False):
for name in dirs:
originaldirs.append(os.path.join(root, name))
global count
count += 1
def rename_first():
target = originaldirs[count]
print(target)
newdirec = '.'
for part in target.split('\\')[1:]:
newdirec += '\\'
newdirec += ' '.join(part.split()[:-1])
newdirec.replace('\\','//')
# os.rename(target,newdirec)
print(newdirec)
while True:
try:
collect()
rename_first()
except IndexError:
print('Fin')
break
试试这个:
从pathlib导入路径
对于路径(“.”.glob(***”)中的路径:
如果path.is_dir():
target=path.parent/“”.join(path.name.split()[:-1])
路径。重命名(目标)
FileExistsError:[WinError 183]无法在文件已经存在的情况下创建文件:“文件”->。
我还应该提到此结构中也有文件,但我只希望它重命名文件夹,而不是文件。@Jamesdeluk更新了代码段。这样,只有目录将被重命名,而任何子级别中的所有文件将保持不变。