简体   繁体   中英

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM