遍历不同的文件夹python

时间:2018-08-07 14:26:30

标签: python for-loop

我想对操作使用txt.file,每个txt.file具有相同的名称,但位于不同的子文件夹中。我试图创建一个包含文件夹名称的列表,并使用os.chdir进行调用,但这不起作用。

??

2 个答案:

答案 0 :(得分:0)

os.chdir(r"//Desktop/foldersforreading/folder{}".format(i))

如果您的文件夹名称是folder1,folder2,...

但是如果您要访问列表中的字符串:

for i in folderlist
    os.chdir(r"//Desktop/foldersforreading/{}".format(i))

如果您想在其中看到“文件夹列表”,也可以添加(有点多余),但是:

for i in folderlist
    os.chdir(r"//Desktop/foldersforreading/{folderlist_i}".format(folderlist_i = i))

string format() function

示例:

some_list = ['this', 'is', 'some', 'list']

for i in range(0,5):
    print(r"//Desktop/foldersforreading/{folderlist_i}".format(folderlist_i = i))

print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')

for i in some_list:
    print(r"//Desktop/foldersforreading/{folderlist_i}".format(folderlist_i = i))

输出:

//Desktop/foldersforreading/0
//Desktop/foldersforreading/1
//Desktop/foldersforreading/2
//Desktop/foldersforreading/3
//Desktop/foldersforreading/4
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//Desktop/foldersforreading/this
//Desktop/foldersforreading/is
//Desktop/foldersforreading/some
//Desktop/foldersforreading/list

答案 1 :(得分:0)

folderlist=["folder1","folder2","folder3","folder4"]
#i=0 #unneeded counter
for i in range(4):

    os.chdir(r"//Desktop/foldersforreading/"+folderlist[i])
    #os.chdir(r"//Desktop/foldersforreading"+"//"+folderlist[i]) #Alternative if above fails
    file=pd.read_table('file.txt',sep=',',header=0, index_col=None)
 #do something 
 #move to next one 
 #i=i+1 #Commented out since you don't need to iterate your counter

尝试上面的代码,它应该可以解决您的问题,并且语法简单,类似于您的要求。