Python,重命名子目录
Python, Renaming Subdirectors
(使用 2.7)
目前遇到问题,我一直在尝试完成 os.walk / os.rename 的过程。但目前,只有主文件附加了 _final,而不是该文件中的所有文件。
例如
Main
---> sub1
-> sub2
-> sub3
需要
Main_final (currently stopping here)
----> sub1_final
-> sub2_final
-> sub3_final
这是我目前的代码,
import shutil
import sys
import os
def rename():
### pseudo
for folderName, subfolders, filenames in os.walk(path, topdown=##???):
for subfolder in subfolders:
print subfolder
os.rename(os.path.join(folderName, subfolders), os.path.join(folderName, subfolders + 'rename'))
print('')
else:
print("Directory does not exist")
if __name__ == '__main__':
copy()
os.walk(fc)
returns 生成器对象,所以如果你在遍历或迭代过程中编辑条目,os.walk
混淆(它使用 dfs 遍历算法,所以之前的堆栈条目不再存在)所以它引发了 StopIteration
您需要获取所有条目并按照条目最深的顺序重命名文件。
import shutil
import sys
import os
from operator import itemgetter
def copy():
print("copy program")
set_path = "D:\test\test1"
os.chdir(set_path)
if os.path.exists(set_path):
fc ='D:\test\test1\final'
working = '_final'
shutil.copytree(set_path, fc)
os.chdir(fc)
stack = [0]
entries = []
for folder, subfolders, files in os.walk(fc):
lev = stack.pop()
for subfolder in subfolders:
entries.append((os.path.join(folder, subfolder), lev + 1))
for file in files:
entries.append((os.path.join(folder, file), lev + 1))
stack.extend([lev + 1]*len(subfolders))
for fpath in map(itemgetter(0), sorted(entries, key=lambda x: -x[1])):
os.rename(fpath, fpath + working)
else:
print("Directory does not exist")
if __name__ == '__main__':
copy()
它在我的系统上有效
遍历树并将 topdown 设置为 False - 首先重命名 sub-directories,最后重命名 top-level 目录,重命名 top-level 目录将不再影响 sub-directories。
If optional argument topdown is True or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If topdown is False, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated.
When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames when topdown is False has no effect on the behavior of the walk, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated.
import os
path = "path/to/folder"
for root, dirs, files in os.walk(path, topdown=False):
for dirname in dirs:
print os.path.join(root, dirname)
os.rename(os.path.join(root, dirname), os.path.join(root, dirname+"_Final"))
(使用 2.7)
目前遇到问题,我一直在尝试完成 os.walk / os.rename 的过程。但目前,只有主文件附加了 _final,而不是该文件中的所有文件。
例如
Main ---> sub1 -> sub2 -> sub3
需要
Main_final (currently stopping here) ----> sub1_final -> sub2_final -> sub3_final
这是我目前的代码,
import shutil
import sys
import os
def rename():
### pseudo
for folderName, subfolders, filenames in os.walk(path, topdown=##???):
for subfolder in subfolders:
print subfolder
os.rename(os.path.join(folderName, subfolders), os.path.join(folderName, subfolders + 'rename'))
print('')
else:
print("Directory does not exist")
if __name__ == '__main__':
copy()
os.walk(fc)
returns 生成器对象,所以如果你在遍历或迭代过程中编辑条目,os.walk
混淆(它使用 dfs 遍历算法,所以之前的堆栈条目不再存在)所以它引发了 StopIteration
您需要获取所有条目并按照条目最深的顺序重命名文件。
import shutil
import sys
import os
from operator import itemgetter
def copy():
print("copy program")
set_path = "D:\test\test1"
os.chdir(set_path)
if os.path.exists(set_path):
fc ='D:\test\test1\final'
working = '_final'
shutil.copytree(set_path, fc)
os.chdir(fc)
stack = [0]
entries = []
for folder, subfolders, files in os.walk(fc):
lev = stack.pop()
for subfolder in subfolders:
entries.append((os.path.join(folder, subfolder), lev + 1))
for file in files:
entries.append((os.path.join(folder, file), lev + 1))
stack.extend([lev + 1]*len(subfolders))
for fpath in map(itemgetter(0), sorted(entries, key=lambda x: -x[1])):
os.rename(fpath, fpath + working)
else:
print("Directory does not exist")
if __name__ == '__main__':
copy()
它在我的系统上有效
遍历树并将 topdown 设置为 False - 首先重命名 sub-directories,最后重命名 top-level 目录,重命名 top-level 目录将不再影响 sub-directories。
If optional argument topdown is True or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If topdown is False, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated.
When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames when topdown is False has no effect on the behavior of the walk, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated.
import os
path = "path/to/folder"
for root, dirs, files in os.walk(path, topdown=False):
for dirname in dirs:
print os.path.join(root, dirname)
os.rename(os.path.join(root, dirname), os.path.join(root, dirname+"_Final"))