我编写了以下代码来迭代文件夹及其文件,并将每个文件夹中的每个文件重命名为文件夹中的文件索引。 E.g每个文件夹中的第一个文件将命名为1.JPG
,第二个文件将命名为2.JPG
,依此类推。文件夹名称是从1到82的整数。我需要文件夹名称来指定os.rename()
中的路径,并且计划从dirs
列表中获取它,因为os.walk(path)
不会遍历目录按顺序。
代码:
import os
import sys
path='/home/srilatha/Desktop/Research_intern/Data_sets/Final'
i=0
for root, dirs, files in os.walk(path):
print(dirs)
print(dirs[i])
#folder_name=dirs[0]
#print(folder_name)
j=0
for name in sorted(files):
j+=1
#print('j=')
#print(j)
print(name)
new=str(j)
new_name=new+'.JPG'
print(new_name)
#os.rename(name,new_name)
i+=1
错误讯息:
/usr/bin/python3.4 /home/srilatha/PycharmProjects/Research_Intern/Sort_images_into_folders.py
['9', '43', '78', '7', '51', '15', '4', '68', '48', '67', '27', '16', '55', '20', '57', '38', '47', '18', '77', '82', '12', '65', '25', '59', '49', '30', '36', '79', '71', '17', '22', '42', '40', '73', '19', '24', '10', '37', '32', '3', '64', '62', '58', '13', '72', '2', '14', '70', '11', '66', '69', '50', '54', '34', '5', '52', '81', '26', '39', '60', '1', '56', '33', '80', '23', '53', '44', '45', '29', '41', '28', '35', '6', '46', '31', '8', '63', '75', '61', '76', '74', '21']
9
[]
Traceback (most recent call last):
File "/home/srilatha/PycharmProjects/Research_Intern/Sort_images_into_folders.py", line 9, in <module>
print(dirs[i])
IndexError: list index out of range
答案 0 :(得分:1)
我想你想要这样的东西?
# Import the os module, for the os.walk function
import os
# Set the directory you want to start from
rootDir = '/Users/heinst'
for dirName, subdirList, fileList in os.walk(rootDir):
print('Found directory: %s' % dirName)
i = 0
for fname in fileList:
print '\t{0} -> {1}'.format(fname, str(i) + os.path.splitext(fname)[1])
i += 1