Hướng dẫn scandir recursive python

Asked 6 years, 11 months ago

Viewed 40k times

Python 3.5's os.scandir[path] function returns lightweight DirEntry objects that are very helpful with information about files. However, it only works for the immediate path handed to it. Is there a way to wrap it in a recursive function so that it visits all subdirectories beneath the given path?

Ben Hoyt

10.3k5 gold badges56 silver badges84 bronze badges

asked Oct 14, 2015 at 20:31

1

You can scan recursively using os.walk[], or if you need DirEntry objects or more control, write a recursive function like scantree[] below:

try:
    from os import scandir
except ImportError:
    from scandir import scandir  # use scandir PyPI module on Python < 3.5

def scantree[path]:
    """Recursively yield DirEntry objects for given directory."""
    for entry in scandir[path]:
        if entry.is_dir[follow_symlinks=False]:
            yield from scantree[entry.path]  # see below for Python 2.x
        else:
            yield entry

if __name__ == '__main__':
    import sys
    for entry in scantree[sys.argv[1] if len[sys.argv] > 1 else '.']:
        print[entry.path]

Notes:

  • There are a few more examples in PEP 471 and in the os.scandir[] docs.
  • You can also add various logic in the for loop to skip directories or files starting with '.' and that kind of thing.
  • You typically want follow_symlinks=false on the is_dir[] calls in recursive functions like this, to avoid symlink loops.
  • On Python 2.x, replace the yield from line with:

    for entry in scantree[entry.path]:
        yield entry
    

answered Oct 14, 2015 at 20:38

Ben HoytBen Hoyt

10.3k5 gold badges56 silver badges84 bronze badges

7

Is python easier for interviews?

The following is based on my knowledge/skills/comfort [or lack thereof] as opposed to INHERENT qualities of the languages.Why Python? Its more pseudocode-like than Java. Easier to just start coding ...

Hướng dẫn python string after index

###IntroductionThe Python string data type is a sequence made up of one or more individual characters that could consist of letters, numbers, whitespace characters, or symbols. Because a string is a ...

What is radians function in python?

❮ Math MethodsExampleConvert different degrees into radians: # Import math Libraryimport math # Convert different degrees into radiansprint[math.radians[180]]print[math.radians[100.03]] ...

Plot two variables in python matplotlib

The matplotlib.pyplot module creates a figure and axes object [see help[plt.subplots] for details] that can be used to create a plot as requested:import matplotlib.pyplot as plt # Impot the relevant ...

How do i convert time to string in python?

The strftime[] method returns a string representing date and time using date, time or datetime object.Example 1: datetime to string using strftime[]The program below converts a datetime object ...

How do you round to 2 digit decimals in python?

You want to round your answer.round[value,significantDigit] is the ordinary solution to do this, however this sometimes does not operate as one would expect from a math perspective when the digit ...

Fibonacci program using recursion in python

A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms.This means to say the nth term ...

In xuống dòng trong python

Hãy nhớ lại đoạn mã của chương trình mà chúng ta viết ở bài học trước: print[Hello World!] Làm thế nào để khi chạy dòng lệnh trên máy tính [hay cụ thể ...

How does threading works in python?

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Threading in PythonPython threading ...

How do you round up in python?

For those who doesnt want to use import.For a given list or any number:x = [2, 2.1, 2.5, 3, 3.1, 3.5, 2.499,2.4999999999, 3.4999999,3.99999999999] You must first evaluate if the number is equal to ...

How do i run a python test in terminal?

Source code: Lib/unittest/__init__.py[If you are already familiar with the basic concepts of testing, you might want to skip to the list of assert methods.]The unittest unit testing framework was ...

Ghép 2 list trong python

import itertools A = list[zip[[1,3,5,7,9],[2,4,6,8,10]]] B = [1,3,5,7,9]+[2,4,6,8,10] C = list[set[[1,3,5,7,9] + [2,4,6,8,10]]] D = [1,3,5,7,9] D.append[[2,4,6,8,10]] E = ...

Is struct available in python?

Educative Answers TeamThe struct module in Python is used to convert native Python data types such as strings and numbers into a string of bytes and vice versa. What this means is that users can ...

Python convert binary to file

I want to convert a bin file to txt file in python.with open[atb.bin, rb] as file: data = file.read[8] datastring = str[data] print[datastring] print[ .join[str[ord[c]] for c in ...

How to calculate auc manually python

How can I obtain the AUC value having fpr and tpr? Fpr and tpr are just 2 floats obtained from these formulas:my_fpr = fp / [fp + tn] my_tpr = tp / [tp + fn] my_roc_auc = auc[my_fpr, my_tpr] I know ...

How do you split a decimal value in python?

I have come up with two statements that can divide positive and negative numbers into integer and fraction without compromising accuracy [bit overflow] and speed.As an example, a positive or negative ...

Hướng dẫn python file open unicode

You have stumbled over the general problem with encodings: How can I tell in which encoding a file is?Nội dung chínhOpening and Closing a File ObjectReading from a FileWriting to a FileCommon ...

Hướng dẫn dịch ngược python

Python là một ngôn ngữ mạnh, hỗ trợ nhiều, cực kì nhiều thư viện, thường dùng để deploy nhanh ứng dụng. Sau khi viết xong 1 file python, ta có thể sử dụng ...

Python add property to object

I want to create a dynamic object [inside another object] in Python and then add attributes to it.I tried:obj = someobject obj.a = object[] setattr[obj.a, somefield, somevalue] but this didnt ...

Hướng dẫn dùng python courses python

Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người. Là ...

Hướng dẫn rotate python

The rotation of a list has been discussed earlier also, but this particular article focuses on shorthands and various short techniques to achieve this in one-liners or one word. This operation is ...

Hướng dẫn python latest version

Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax ...

Hướng dẫn dùng dump definition python

Nội dung chínhNội dung chínhGiới thiệu về JSONVí dụ về Import JSON, khai báo, đọc và in dữ liệu JSON bằng PythonVí dụ về ghi dữ liệu JSON trong PythonVí dụ ...

Hướng dẫn python switch

Đã đăng vào thg 3 22, 2019 8:46 SA 1 phút đọc 1 Giới thiệu.Khi mình tìm hiểu python ta đã thấy một điều quái lạ là vì sao python không định nghĩa các function ...

Vscode generate getters and setters python

This is my class called manager I want to generate automatically getter and setter in python vs code.class Manager: def __init__[self, name, salary, bonus]: self.bonus = bonus ...

Hướng dẫn dùng python ide python

Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người. Là ...

Hướng dẫn python popup error message

I have a program and if you enter the ip address wrong the shell window will produce a socket error. I want to create a pop up message box that runs anytime I see a certain error in the shell window. ...

Hướng dẫn dùng acsend math python

Giới thiệu về kỹ thuật xuống dốc [gradient descent]Trong phần 1, chúng ta sử dụng kỹ thuật xuống dốc để tìm điểm cực tiểu của hàm mất mát trong phương ...

Hướng dẫn python bytearray to bytes

Many different types of data objects are supported by Python. Two of them are the objects bytearray and bytes. The bytearray[] function returns an array object of bytes. This object is changeable and ...

How do i install pip for python 3?

edit: Manual installation and use of setuptools is not the standard process anymore.If youre running Python 2.7.9+ or Python 3.4+Congrats, you should already have pip installed. If you do not, read ...

Working with pandas in python

This is a short introduction to pandas, geared mainly for new users. You can see more complex recipes in the Cookbook.Customarily, we import as follows:In [1]: import numpy as np In [2]: import ...

Chủ Đề