【问题标题】:Renaming / Restructuring the layout of file names in a directory重命名/重构目录中文件名的布局
【发布时间】:2019-07-07 22:20:43
【问题描述】:
import os

input_path = raw_input('Input file path here : ')

os.chdir(input_path)


for f in os.listdir(input_path):
    print f

我有这样枚举的“UDIM”纹理文件

1001_Base_Color.png, 1002_Base_Color.png, 1003_Base_Color.png.

我的目标是遍历目录中的每个文件并重新定位文件末尾的数字。 name ---> Base_Color_1001.png

感谢任何见解!

谢谢

【问题讨论】:

  • 每个文件的开头是否正好有四个数字后跟一个下划线? (另外,您运行的是 Linux 还是 Windows?)
  • 是的,所有 UDIM 号码都是 4 位数字。 Linux

标签: python file directory batch-rename renaming


【解决方案1】:

您可以用下划线分割每个文件名,然后在将数字附加到标记末尾后用下划线重新连接它们:

for f in os.listdir(input_path):
    name, ext = os.path.splitext(f)
    os.rename(f, ''.join(name.partition('_')[::-1]) + ext)

【讨论】:

  • 文件 "./NamingTool.py", line 12 num, *tokens = name.split('_') ^ SyntaxError: invalid syntax getting a syntax error on the *
  • @AMist 将最后两行替换为:os.rename(f, ''.join(name.partition('_')[::-1]) + ext)。
  • @ekhumoro 确实与 Python 2 兼容的好解决方案。谢谢。
  • @AMist 该代码需要 Python 3。我现在使用与 Python 2 兼容的 ekhumoro 解决方案更新了我的答案。
猜你喜欢
  • 2015-10-08
  • 2013-12-05
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
  • 2013-06-12
  • 2018-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多