简体   繁体   English

Python:遍历多个词典中的文件

[英]Python: Iterate through Files in Multiple Dictionaries

I have a number of files in a dictionary that I want to run a script on. 我要在其上运行脚本的词典中有许多文件。 Ordinarily, I would us 'os.listdir()' to list the files in my current working directory, and then tell my script to run on those files. 通常,我会使用“ os.listdir()”列出当前工作目录中的文件,然后告诉我的脚本在这些文件上运行。

For instance: 例如:

dir = os.listdir():
for i in dir:
  do stuff

However, I want to run the script on these files when i am not in the current working directory. 但是,当我不在当前工作目录中时,我想在这些文件上运行脚本。 This will be so I can iterate through multiple folders later on. 这样,以后我就可以遍历多个文件夹。 Any suggestions? 有什么建议么?

listdir() takes a path parameter. listdir()采用path参数。 You could use something like this: 您可以使用如下形式:

filelist1 = os.listdir("/home/user/directory1")
filelist2 = os.listdir("/home/user/directory2")

In order to read all files that are available under a directory: 为了读取目录下可用的所有文件:

from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

To list all available subdirs in a directory: 要列出目录中所有可用的子目录:

from os import listdir
from os.path import isdir, join

subdirs = [name for name in listdir(parent_dir) if isdir(join(parent_dir, name))]

Now let's combine those puzzles to list files only from sub-dirs of parent directory: 现在,让我们结合这些难题,仅从父目录的子目录列出文件:

from os import listdir
from os.path import isfile, join, isdir

parent_dir = "/foo/bar"
dirs = [name for name in listdir(parent_dir) if isdir(join(parent_dir, name))]
onlyfiles = []

for dir in dirs:
    f = [f for f in listdir(dir) if isfile(join(dir, f))]
    onlyfiles += f

print(onlyfiles)

Example output: 输出示例:

$ python dummy.py 
['Dockerfile', 'docker-compose.yml', '53009790.py', 'MOCK_DATA.csv', '53021557.py', '53023079.py']
$ python3 dummy.py 
['Dockerfile', 'docker-compose.yml', '53009790.py', 'MOCK_DATA.csv', '53021557.py', '53023079.py']

You can also try use glob module, as it does pattern matching. 您也可以尝试使用glob模块,因为它可以进行模式匹配。

>>> import glob
>>> print(glob.glob('/home/rszamszur/*.sh'))
['/home/rszamszur/work-monitors.sh', '/home/rszamszur/default-monitor.sh', '/home/rszamszur/home-monitors.sh']

Key difference between OS module and glob is that OS will work for all systems, where glob only for Unix like. OS模块和glob之间的主要区别在于OS将适用于所有系统,而glob仅适用于Unix。

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

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