我已经阅读了其他一些帖子,并尝试了这些答案中的代码,但无法让我的工作
这是我的文件结构:
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的),因此脚本结束
使用topdown=False
,我得到一个错误:
FileNotFoundError: [WinError 3] The system cannot find the path specified: '.\\motherfile g934uth98t\\kid file fh984bvt34ynt\\something elsee goes here 98573v4985hy4' -> '.\\motherfile\\kid file\\something elsee goes 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
试试这个:
相关问题 更多 >
编程相关推荐