文件在python中行走

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4582550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:26:48  来源:igfitidea点击:

file walking in python

python

提问by Aaron Yodaiken

So, I've got a working solution, but it's ugly and seems un-idiomatic. The problem is this:

所以,我有一个可行的解决方案,但它很丑陋而且似乎不习惯。问题是这样的:

For a directory tree, where every directory is set up to have:

对于目录树,其中每个目录都设置为:

  • 1 .xcfile
  • at least 1 .xfile
  • any number of directories which follow the same format
  • 1 个.xc文件
  • 至少 1 个.x文件
  • 任意数量的遵循相同格式的目录

and nothing else. I'd like to, given the root path and walk the tree applying xc()to the contents of .xcfies, xto the contents to .xfiles, and then doing the same thing to child folders' contents.

没有别的。我想,给定根路径并遍历树应用xc().xcfiesx的内容,到.x文件的内容,然后对子文件夹的内容执行相同的操作。

Actual code with explanation would be appreciated.

带有解释的实际代码将不胜感激。

Thanks!

谢谢!

采纳答案by Andrew Jaffe

The function os.walkrecursively walks through a directory tree, returning all file and subdirectory names.

该函数os.walk递归遍历目录树,返回所有文件和子目录名称。

So all you have to do is detect the .xand .xcextensions from the filenames and apply your functions when they do (untested code follows):

因此,您所要做的就是检测文件名中的.x.xc扩展名并在它们执行时应用您的函数(未经测试的代码如下):

import os

for dirpath, dnames, fnames in os.walk("./"):
    for f in fnames:
        if f.endswith(".x"):
            x(os.path.join(dirpath, f))
        elif f.endswith(".xc"):
            xc(os.path.join(dirpath,f))

This assumes xand xccan be called on filenames; alternately you can read the contents first and pass that as a string to the functions.

这假设x并且xc可以在文件名上调用;或者,您可以先读取内容并将其作为字符串传递给函数。

回答by Matthew Iselin

You could use a dict to hold an extension -> function mapping:

您可以使用 dict 来保存扩展 -> 函数映射:

funcMap = {".xc" : xc,
           ".x"  : x}

Then you create a recursive function that takes a single directory, gets the list of files n that directory, and determines the extension of each file:

然后创建一个递归函数,该函数采用单个目录,获取该目录中的文件列表,并确定每个文件的扩展名:

def iterateDir(s):

    l = dir.list(s) # Not a real function!

    for entry in l:
        ext = entry.extension() # Not a real function!

Now, in this for loop you need to determine if the entry is a file or directory, and perform the right action:

现在,在这个 for 循环中,您需要确定条目是文件还是目录,并执行正确的操作:

        if isdir(entry):
            iterateDir(entry)
        elif ext in funcMap.keys():
            funcMap[ext]()

This should work for what you want to do.

这应该适用于您想要做的事情。

Disclaimer- can't promise all of this is valid Python. It's mostly psuedocode with Python-like syntax. You should be able to get the idea of what to do from this though.

免责声明- 不能保证所有这些都是有效的 Python。它主要是具有类似 Python 语法的伪代码。不过,您应该能够了解该怎么做。

回答by Andrew

Seems like a good place to use recursion:

似乎是使用递归的好地方:

import os
def process_directory(dirName):
    """Recursively process all .xc and .x files in a parent directory and its
    subdirectories"""
    dirName = os.path.abspath(dirName)
    for f in os.listdir(dirName):
        f = os.path.join(dirName, f)
        baseName, ext = os.path.splitext(f)
        if ext == '.xc':
            print "Processing [", f, "]"
            xc(f)
        elif ext == '.x':
            print "Processing [", f, "]"
            x(f)
        elif os.path.isdir(f):
            print "\nDescending into directory", f
            process_directory(dirName=os.path.join(dirName, f))
        else:
            print "Not processing", f

I hope I haven't missed the point of your question.

我希望我没有错过你问题的重点。

回答by albertov

import os

# your functions
def xc(contents): ....
def x(contents): ....

# store function references in a dict to dispatch, this is a common python idiom
funcMap = {'.xc': xc, '.x':x}

for dirpath, dirnames, filenames in os.walk(someDir):
    # use os.walk to iterate someDir's contents recursively. No
    # need to implement recursion yourself if stdlib does it for you
    for f in filenames:
        ext = os.path.splitext(f)[1]
        try:
            function = funcMap[ext]
        except KeyError:
             # no function to process files with extension 'ext', ignore it
             pass
        else:
            abspath = os.path.join(dirpath, f)
            with open(abspath) as f:
                function(f.read())