开发者

Python - Listing files in folders - path names with a variable

I'm very very new to this. I'm using python and I want to list files in a number of different folders (using windows)

In my first go I had loads of path variables. Each path had its own variable. It worked but this seemed like a long winded way of doing it. As the paths are all the same apart from the folder name, I tried this:

import os

folder = ["folderA", "folderB", "folderC", "folderD"]
path1 = input('//server/files/"%s"/data' % (folder))

开发者_开发技巧def list_sp_files():
    for filename in os.listdir(path1):
        print path1, filename

print "reporter"
list_sp_files()

I understand why it doesn't work, but I don't understand how I make it work.


Something like this perhaps?

folders = ["folderA", "folderB", "folderC", "folderD"]
def list_sp_files():
    for folder in folders:
        path = '//server/files/%s/data' % (folder)
        for filename in os.listdir(path):
            print path, filename


Try changing your path1 to something like:

path1 = ["//server/files/%s/data" % f for f in folder]

and changing list_sp_files() to something like:

def list_sp_files(path_list):
    for path in path_list:
        for filename in os.listdir(path):
            print path, filename

and call it via

list_sp_files(path1)

Basically this answer makes the path1 variable a list of strings with a generator expression - it creates a list by iterating through the folder list and for each item there, running "//server/files/%s/data" % f.

The changed list_sp_files() simply iterates through the list of paths given to it and prints all of the contents from os.listdir().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜