python中list的索引错误

2024-04-16 19:25:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了以下代码来遍历文件夹及其文件,并将每个文件夹中的每个文件重命名为文件夹中文件的索引。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

错误消息:

^{pr2}$

Tags: 文件path代码nameimport文件夹newfor
1条回答
网友
1楼 · 发布于 2024-04-16 19:25:02

我想你想要这样的东西?在

# 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

相关问题 更多 >