创建一个名为CarItemsCopy的CarItems树的副本,其中所有文件都位于文件名的一部分中,而不是位于以年命名的目录中,而年份则完全不存在。代替其中一些示例:
CarItems/Chevrolet/Chevelle/2011/parts.txt
CarItems/Chevrolet/Chevelle/1982/parts.txt
CarItems/Chevrolet/Volt/1994/parts.txt
它应该看起来像这样:
CarItemsCopy/Chevrolet/Chevelle/parts-2011.txt
CarItems/Chevrolet/Chevelle/parts-1982.txt
CarItems/Chevrolet/Volt/parts-1994.txt
使用Python执行此操作(您无法通过手动重新排列来创建副本)。您可以使用os模块的walk生成器。提示:您可能会发现os.path模块的split函数会有所帮助。您不必使用它。
这是到目前为止我得到的代码:
shutil.copytree("CarItems", "CarItemsCopy")
for dirpath, dirnames, filenames in os.walk("CarItemsCopy"):
for ifile in filenames:
os.path.split(dirpath)
现在,我想我应该使用os.path.join()将txt文件与年份合并,但是我什至不确定自己是否走上了正确的轨道。此外,年份是一个子目录,我不知道是否需要删除它?谢谢您的帮助!!附言让我知道我是否至少接近! :)
尽管您可以直接找出新的文件名,但您确实需要步行才能到达所有文件名。
伪代码:
# Make a list of filenames with os.walk
# For each filename in that list:
# If the filename matches a regex of ending with four digits, slash, name
# make the new filename
# use os.rename to move the original file to the new file.
您需要制作一个单独的列表,而不仅仅是for name in os.walk...
,因为我们将不断更改内容。
使用Regex101创建正则表达式,我们得到了一个解决方案。您可能需要先尝试一下,然后再看此:
import os
import re
pattern = r'(.*)(\\|/)(\d\d\d\d)(\\|/)(\w+)(\.txt)'
# Note r'..' means raw, or take backslashes literally so the regex is correct.
filenames = [ os.path.join(dir_, name)
for (dir_, _, names) in os.walk('.')
for name in names ]
# Note 'dir_' because dir is reserved word
# Note '_' as pythonic way of saying 'an ignored value'
# Note for loops are in same order in list comprehension as they would be in code
for filename in filenames:
m = re.match(pattern, filename)
if m:
front, sep1, year, sep2, name, ext = m.groups()
new_filename = f'{front}{sep1}{name}-{year}{ext}'
# print(f'rename {filename} to {new_filename}')
os.rename(filename, new_filename)
保持骇客!记笔记。
在应该看起来像部分中,我认为您犯了一个错误。 CarItemsCopy
下仅存在一个目录,另一个将被重命名。
任务:
[创建名为CarItems
的CarItemsCopy
树的副本,其中所有文件,而不是位于以年命名的目录中,而是将年作为文件名的一部分,而完全不存在年目录。]
Path
,shutil
和os
模块应简化任务:
# The Path to our script. Assuming the script and folders exist in the same location.
script_dir = Path(os.path.dirname(os.path.abspath(__file__)))
source_dir = script_dir.joinpath("Caritems")
for folder in source_dir.iterdir():
for subfolder in folder.iterdir():
subfolder_with_parts = subfolder.joinpath("parts.txt")
if subfolder_with_parts.exists(): # Only continue if parts.txt exists.
car_copy_root = Path(script_dir)
ext = {subfolder_with_parts.stem} # In this case the .txt file
parts = Path(f"CarItemsCopy//{folder.stem}//parts-{subfolder.stem}.{ext}")
car_copy = car_copy_root.joinpath(parts)
car_copy.parent.mkdir(parents=True, exist_ok=True)
copy2(subfolder_with_parts, car_copy) # Will attempt to copy the metadata.