【发布时间】:2017-07-30 21:24:42
【问题描述】:
我创建了一个脚本来重命名给定目录中的索引文件
例如,如果目录有以下文件 >> (bar001.txt, bar004.txt, bar007.txt, foo2.txt, foo5.txt, morty.dat, rick.py)。我的脚本应该能够“仅”重命名索引文件并像这样关闭间隙>>(bar001.txt、bar002.txt、bar003.txt、foo1.txt、foo2.txt...)。
我把完整的脚本放在下面,但它不起作用。该错误是合乎逻辑的,因为没有给出错误消息,但目录中的文件保持不变。
#! python3
import os, re
working_dir = os.path.abspath('.')
# A regex pattern that matches files with prefix,numbering and then extension
pattern = re.compile(r'''
^(.*?) # text before the file number
(\d+) # file index
(\.([a-z]+))$ # file extension
''',re.VERBOSE)
# Method that renames the items of an array
def rename(array):
for i in range(len(array)):
matchObj = pattern.search(array[i])
temp = list(matchObj.group(2))
temp[-1] = str(i+1)
index = ''.join(temp)
array[i] = matchObj.group(1) + index + matchObj.group(3)
return(array)
array = []
directory = sorted(os.listdir('.'))
for item in directory:
matchObj = pattern.search(item)
if not matchObj:
continue
if len(array) == 0 or matchObj.group(1) in array[0]:
array.append(item)
else:
temp = array
newNames = rename(temp)
for i in range(len(temp)):
os.rename(os.path.join(working_dir,temp[i]),
os.path.join(working_dir,newNames[i]))
array.clear() #reset array for other files
array.append(item)
【问题讨论】:
-
我假设你也想要
bar005.txt和bar006.txt? -
将它们重命名为什么?
-
其实,没有。您打算通过重命名以后的文件来缩小差距。你的想法有点任务重。一旦我或者如果我克服了这个问题,我可能会考虑自己解决它。
-
例如 spam01, spam03 , spam04 应该重命名为 spam01, spam02, spam 03。这就是我通过重命名来填补空白的意思。所以基本上,使用第一个文件的格式和第一个文件的索引重命名后面的文件。
-
好的,那么如果有三个以
spam开头的文件,它们应该以01、02、03结尾。
标签: python python-3.x filesystems file-management