简体   繁体   English

Python - 列出文件夹中的文件 - 带有变量的路径名

[英]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) 我正在使用python,我想列出许多不同文件夹中的文件(使用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更改为:

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

and changing list_sp_files() to something like: 并将list_sp_files()更改为:

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 . 基本上这个答案使path1变量成为一个带有生成器表达式的字符串列表 - 它通过迭代folder列表创建一个列表,并为那里的每个项目运行"//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() . 更改后的list_sp_files()只是迭代给定的路径列表,并打印os.listdir()所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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