Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

file walking in python

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 .xc file
  • at least 1 .x file
  • any number of directories which follow the same format

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

Actual code with explanation would be appreciated.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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 x and xc can be called on filenames; alternately you can read the contents first and pass that as a string to the functions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...