How to traverse through the files in a directory?

前端 未结 9 1768
离开以前
离开以前 2020-11-30 11:34

I have a directory logfiles. I want to process each file inside this directory using a Python script.

for file in directory:
      # do something
         


        
9条回答
  •  没有蜡笔的小新
    2020-11-30 12:01

    In Python 2, you can try something like:

    import os.path
    
    def print_it(x, dir_name, files):
        print dir_name
        print files
    
    os.path.walk(your_dir, print_it, 0)
    

    Note: the 3rd argument of os.path.walk is whatever you want. You'll get it as the 1st arg of the callback.

    In Python 3 os.path.walk has been removed; use os.walk instead. Instead of taking a callback, you just pass it a directory and it yields (dirpath, dirnames, filenames) triples. So a rough equivalent of the above becomes

    import os
    
    for dirpath, dirnames, filenames in os.walk(your_dir):
        print dirpath
        print dirnames
        print filenames
    

提交回复
热议问题