How do you walk through the directories using python?

前端 未结 4 1484
长情又很酷
长情又很酷 2020-12-15 17:23

I have a folder called notes, naturally they will be categorized into folders, and within those folders there will also be sub-folders for sub categories. Now my problem is

4条回答
  •  -上瘾入骨i
    2020-12-15 17:43

    I've come across this question multiple times, and none of the answers satisfy me - so created a script for that. Pytohn is very cumbersome to use when it comes to walking through directories.

    Here's how it can be used:

    import file_walker
    
    
    for f in file_walker.walk("/a/path"):
         print(f.name, f.full_path) # Name is without extension
         if f.isDirectory: # Check if object is directory
             for sub_f in f.walk(): # Easily walk on new levels
                 if sub_f.isFile: # Check if object is file (= !isDirectory)
                     print(sub_f.extension) # Print file extension
                     with sub_f.open("r") as open_f: # Easily open file
                         print(open_f.read())
    

提交回复
热议问题