Đẹp hơn nhiều so với ở trên, vì bạn không cần một số os.path.join [] và bạn sẽ nhận được đường dẫn đầy đủ [nếu bạn muốn], bạn có thể làm điều này trong Python 3.5 trở lên.Python 3.5 and above.
subfolders = [ f.path for f in os.scandir[folder] if f.is_dir[] ]
Điều này sẽ cung cấp cho con đường hoàn chỉnh đến thư mục con. Nếu bạn chỉ muốn tên của thư mục con
os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
0 thay vì os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
1//docs.python.org/3/library/os.html#os.scandir
Hơi OT: Trong trường hợp bạn cần tất cả các thư mục con đệ quy và/hoặc tất cả các tệp một cách đệ quy, hãy xem chức năng này, nhanh hơn
os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
2 & os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
3 và sẽ trả về danh sách tất cả các thư mục con cũng như tất cả các tệp bên trong các tệp đó [phụ] Các thư mục con: //stackoverflow.com/a/59803793/2441026all subfolder recursively and/or all files recursively, have a look at this function, that is faster than os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
2 & os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
3 and will return a list of all subfolders as well as all files inside those [sub-]subfolders:
//stackoverflow.com/a/59803793/2441026Trong trường hợp bạn chỉ muốn tất cả các thư mục con đệ quy:all subfolders recursively:
def fast_scandir[dirname]:
subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
for dirname in list[subfolders]:
subfolders.extend[fast_scandir[dirname]]
return subfolders
Trả về một danh sách tất cả các thư mục con với đường dẫn đầy đủ của chúng. Điều này một lần nữa nhanh hơn
os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
2 và nhanh hơn rất nhiều so với os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
3.Phân tích tất cả các chức năng
TL; DR: - Nếu bạn muốn nhận tất cả các thư mục con ngay lập tức cho một thư mục sử dụng
os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
6. - Nếu bạn muốn có được tất cả các thư mục con, thậm chí là lồng nhau, hãy sử dụng os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
2 hoặc - nhanh hơn một chút - hàm os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
8 ở trên. - Không bao giờ sử dụng os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
2 chỉ cho các thư mục cấp cao nhất, vì nó có thể chậm hơn hàng trăm [!] Của thời gian so với os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
6.- If you want to get all immediate subdirectories for a folder use
os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
6.- If you want to get all subdirectories, even nested ones, use
os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
2 or - slightly faster - the os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
8 function above.- Never use
os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
2 for only top-level subdirectories, as it can be hundreds[!] of times slower than os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
6.- Nếu bạn chạy mã bên dưới, hãy đảm bảo chạy nó một lần để HĐH của bạn sẽ truy cập thư mục, loại bỏ kết quả và chạy thử nghiệm, nếu không, kết quả sẽ được vặn vẹo.
- Bạn có thể muốn trộn các cuộc gọi chức năng, nhưng tôi đã thử nghiệm nó và nó không thực sự quan trọng.
- Tất cả các ví dụ sẽ đưa ra đường dẫn đầy đủ đến thư mục. Ví dụ Pathlib dưới dạng đối tượng đường dẫn [Windows].
- Yếu tố đầu tiên của
2 sẽ là thư mục cơ sở. Vì vậy, bạn sẽ không chỉ nhận được các thư mục con. Bạn có thể sử dụngos.scandir took 1 ms. Found dirs: 439 os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder. glob.glob took 20 ms. Found dirs: 439 pathlib.iterdir took 18 ms. Found dirs: 439 os.listdir took 18 ms. Found dirs: 439
2 để loại bỏ nó.# -*- coding: utf-8 -*- # Python 3 import time import os from glob import glob from pathlib import Path directory = r"" RUNS = 1 def run_os_walk[]: a = time.time_ns[] for i in range[RUNS]: fu = [x[0] for x in os.walk[directory]] print[f"os.walk\t\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_glob[]: a = time.time_ns[] for i in range[RUNS]: fu = glob[directory + "/*/"] print[f"glob.glob\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_pathlib_iterdir[]: a = time.time_ns[] for i in range[RUNS]: dirname = Path[directory] fu = [f for f in dirname.iterdir[] if f.is_dir[]] print[f"pathlib.iterdir\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_os_listdir[]: a = time.time_ns[] for i in range[RUNS]: dirname = Path[directory] fu = [os.path.join[directory, o] for o in os.listdir[directory] if os.path.isdir[os.path.join[directory, o]]] print[f"os.listdir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_os_scandir[]: a = time.time_ns[] for i in range[RUNS]: fu = [f.path for f in os.scandir[directory] if f.is_dir[]] print[f"os.scandir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len[fu]}"] if __name__ == '__main__': run_os_scandir[] run_os_walk[] run_glob[] run_pathlib_iterdir[] run_os_listdir[]
- Không có kết quả nào sẽ sử dụng phân loại tự nhiên. Điều này có nghĩa là kết quả sẽ được sắp xếp như thế này: 1, 10, 2. Để có được sự phân loại tự nhiên [1, 2, 10], xin vui lòng xem //stackoverflow.com/a/48030307/2441026. This means results will be sorted like this: 1, 10, 2. To get natural sorting [1, 2, 10], please have a look at //stackoverflow.com/a/48030307/2441026
Kết quả::
os.scandir took 1 ms. Found dirs: 439
os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob took 20 ms. Found dirs: 439
pathlib.iterdir took 18 ms. Found dirs: 439
os.listdir took 18 ms. Found dirs: 439
Được thử nghiệm với W7X64, Python 3.8.1.
# -*- coding: utf-8 -*-
# Python 3
import time
import os
from glob import glob
from pathlib import Path
directory = r""
RUNS = 1
def run_os_walk[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = [x[0] for x in os.walk[directory]]
print[f"os.walk\t\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_glob[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = glob[directory + "/*/"]
print[f"glob.glob\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_pathlib_iterdir[]:
a = time.time_ns[]
for i in range[RUNS]:
dirname = Path[directory]
fu = [f for f in dirname.iterdir[] if f.is_dir[]]
print[f"pathlib.iterdir\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_os_listdir[]:
a = time.time_ns[]
for i in range[RUNS]:
dirname = Path[directory]
fu = [os.path.join[directory, o] for o in os.listdir[directory] if os.path.isdir[os.path.join[directory, o]]]
print[f"os.listdir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_os_scandir[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = [f.path for f in os.scandir[directory] if f.is_dir[]]
print[f"os.scandir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len[fu]}"]
if __name__ == '__main__':
run_os_scandir[]
run_os_walk[]
run_glob[]
run_pathlib_iterdir[]
run_os_listdir[]
Trong bài viết này, chúng ta sẽ thấy cách liệt kê tất cả các tệp của một thư mục trong Python. Có nhiều cách để liệt kê các tập tin của một thư mục. Trong bài viết này, chúng tôi sẽ sử dụng các phương thức sau & nbsp; bốn phương thức.four methods.
3: Trả về danh sách các tệp và thư mục có trong một đường dẫn thư mục được chỉ định.# -*- coding: utf-8 -*- # Python 3 import time import os from glob import glob from pathlib import Path directory = r"" RUNS = 1 def run_os_walk[]: a = time.time_ns[] for i in range[RUNS]: fu = [x[0] for x in os.walk[directory]] print[f"os.walk\t\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_glob[]: a = time.time_ns[] for i in range[RUNS]: fu = glob[directory + "/*/"] print[f"glob.glob\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_pathlib_iterdir[]: a = time.time_ns[] for i in range[RUNS]: dirname = Path[directory] fu = [f for f in dirname.iterdir[] if f.is_dir[]] print[f"pathlib.iterdir\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_os_listdir[]: a = time.time_ns[] for i in range[RUNS]: dirname = Path[directory] fu = [os.path.join[directory, o] for o in os.listdir[directory] if os.path.isdir[os.path.join[directory, o]]] print[f"os.listdir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_os_scandir[]: a = time.time_ns[] for i in range[RUNS]: fu = [f.path for f in os.scandir[directory] if f.is_dir[]] print[f"os.scandir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len[fu]}"] if __name__ == '__main__': run_os_scandir[] run_os_walk[] run_glob[] run_pathlib_iterdir[] run_os_listdir[]
4: Tập hợp lại danh sách tất cả các tệp trong thư mục và thư mục con.# -*- coding: utf-8 -*- # Python 3 import time import os from glob import glob from pathlib import Path directory = r"" RUNS = 1 def run_os_walk[]: a = time.time_ns[] for i in range[RUNS]: fu = [x[0] for x in os.walk[directory]] print[f"os.walk\t\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_glob[]: a = time.time_ns[] for i in range[RUNS]: fu = glob[directory + "/*/"] print[f"glob.glob\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_pathlib_iterdir[]: a = time.time_ns[] for i in range[RUNS]: dirname = Path[directory] fu = [f for f in dirname.iterdir[] if f.is_dir[]] print[f"pathlib.iterdir\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_os_listdir[]: a = time.time_ns[] for i in range[RUNS]: dirname = Path[directory] fu = [os.path.join[directory, o] for o in os.listdir[directory] if os.path.isdir[os.path.join[directory, o]]] print[f"os.listdir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_os_scandir[]: a = time.time_ns[] for i in range[RUNS]: fu = [f.path for f in os.scandir[directory] if f.is_dir[]] print[f"os.scandir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len[fu]}"] if __name__ == '__main__': run_os_scandir[] run_os_walk[] run_glob[] run_pathlib_iterdir[] run_os_listdir[]
5: Trả về các mục nhập thư mục cùng với thông tin thuộc tính tệp.# -*- coding: utf-8 -*- # Python 3 import time import os from glob import glob from pathlib import Path directory = r"" RUNS = 1 def run_os_walk[]: a = time.time_ns[] for i in range[RUNS]: fu = [x[0] for x in os.walk[directory]] print[f"os.walk\t\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_glob[]: a = time.time_ns[] for i in range[RUNS]: fu = glob[directory + "/*/"] print[f"glob.glob\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_pathlib_iterdir[]: a = time.time_ns[] for i in range[RUNS]: dirname = Path[directory] fu = [f for f in dirname.iterdir[] if f.is_dir[]] print[f"pathlib.iterdir\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_os_listdir[]: a = time.time_ns[] for i in range[RUNS]: dirname = Path[directory] fu = [os.path.join[directory, o] for o in os.listdir[directory] if os.path.isdir[os.path.join[directory, o]]] print[f"os.listdir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_os_scandir[]: a = time.time_ns[] for i in range[RUNS]: fu = [f.path for f in os.scandir[directory] if f.is_dir[]] print[f"os.scandir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len[fu]}"] if __name__ == '__main__': run_os_scandir[] run_os_walk[] run_glob[] run_pathlib_iterdir[] run_os_listdir[]
6: Mô -đun GLOB đến & NBSP; Liệt kê các tệp và thư mục có tên theo một mẫu cụ thể.# -*- coding: utf-8 -*- # Python 3 import time import os from glob import glob from pathlib import Path directory = r"" RUNS = 1 def run_os_walk[]: a = time.time_ns[] for i in range[RUNS]: fu = [x[0] for x in os.walk[directory]] print[f"os.walk\t\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_glob[]: a = time.time_ns[] for i in range[RUNS]: fu = glob[directory + "/*/"] print[f"glob.glob\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_pathlib_iterdir[]: a = time.time_ns[] for i in range[RUNS]: dirname = Path[directory] fu = [f for f in dirname.iterdir[] if f.is_dir[]] print[f"pathlib.iterdir\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_os_listdir[]: a = time.time_ns[] for i in range[RUNS]: dirname = Path[directory] fu = [os.path.join[directory, o] for o in os.listdir[directory] if os.path.isdir[os.path.join[directory, o]]] print[f"os.listdir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_os_scandir[]: a = time.time_ns[] for i in range[RUNS]: fu = [f.path for f in os.scandir[directory] if f.is_dir[]] print[f"os.scandir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len[fu]}"] if __name__ == '__main__': run_os_scandir[] run_os_walk[] run_glob[] run_pathlib_iterdir[] run_os_listdir[]
Cách liệt kê tất cả các tệp của một thư mục
Nhận một danh sách các tập tin của một thư mục rất dễ dàng như PIE! Sử dụng các hàm
# -*- coding: utf-8 -*-
# Python 3
import time
import os
from glob import glob
from pathlib import Path
directory = r""
RUNS = 1
def run_os_walk[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = [x[0] for x in os.walk[directory]]
print[f"os.walk\t\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_glob[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = glob[directory + "/*/"]
print[f"glob.glob\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_pathlib_iterdir[]:
a = time.time_ns[]
for i in range[RUNS]:
dirname = Path[directory]
fu = [f for f in dirname.iterdir[] if f.is_dir[]]
print[f"pathlib.iterdir\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_os_listdir[]:
a = time.time_ns[]
for i in range[RUNS]:
dirname = Path[directory]
fu = [os.path.join[directory, o] for o in os.listdir[directory] if os.path.isdir[os.path.join[directory, o]]]
print[f"os.listdir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_os_scandir[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = [f.path for f in os.scandir[directory] if f.is_dir[]]
print[f"os.scandir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len[fu]}"]
if __name__ == '__main__':
run_os_scandir[]
run_os_walk[]
run_glob[]
run_pathlib_iterdir[]
run_os_listdir[]
7 và # -*- coding: utf-8 -*-
# Python 3
import time
import os
from glob import glob
from pathlib import Path
directory = r""
RUNS = 1
def run_os_walk[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = [x[0] for x in os.walk[directory]]
print[f"os.walk\t\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_glob[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = glob[directory + "/*/"]
print[f"glob.glob\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_pathlib_iterdir[]:
a = time.time_ns[]
for i in range[RUNS]:
dirname = Path[directory]
fu = [f for f in dirname.iterdir[] if f.is_dir[]]
print[f"pathlib.iterdir\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_os_listdir[]:
a = time.time_ns[]
for i in range[RUNS]:
dirname = Path[directory]
fu = [os.path.join[directory, o] for o in os.listdir[directory] if os.path.isdir[os.path.join[directory, o]]]
print[f"os.listdir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_os_scandir[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = [f.path for f in os.scandir[directory] if f.is_dir[]]
print[f"os.scandir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len[fu]}"]
if __name__ == '__main__':
run_os_scandir[]
run_os_walk[]
run_glob[]
run_pathlib_iterdir[]
run_os_listdir[]
8 của mô -đun HĐH để liệt kê tất cả các tệp của thư mục. Đây là các bước.# -*- coding: utf-8 -*-
# Python 3
import time
import os
from glob import glob
from pathlib import Path
directory = r""
RUNS = 1
def run_os_walk[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = [x[0] for x in os.walk[directory]]
print[f"os.walk\t\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_glob[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = glob[directory + "/*/"]
print[f"glob.glob\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_pathlib_iterdir[]:
a = time.time_ns[]
for i in range[RUNS]:
dirname = Path[directory]
fu = [f for f in dirname.iterdir[] if f.is_dir[]]
print[f"pathlib.iterdir\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_os_listdir[]:
a = time.time_ns[]
for i in range[RUNS]:
dirname = Path[directory]
fu = [os.path.join[directory, o] for o in os.listdir[directory] if os.path.isdir[os.path.join[directory, o]]]
print[f"os.listdir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_os_scandir[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = [f.path for f in os.scandir[directory] if f.is_dir[]]
print[f"os.scandir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len[fu]}"]
if __name__ == '__main__':
run_os_scandir[]
run_os_walk[]
run_glob[]
run_pathlib_iterdir[]
run_os_listdir[]
7 and # -*- coding: utf-8 -*-
# Python 3
import time
import os
from glob import glob
from pathlib import Path
directory = r""
RUNS = 1
def run_os_walk[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = [x[0] for x in os.walk[directory]]
print[f"os.walk\t\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_glob[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = glob[directory + "/*/"]
print[f"glob.glob\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_pathlib_iterdir[]:
a = time.time_ns[]
for i in range[RUNS]:
dirname = Path[directory]
fu = [f for f in dirname.iterdir[] if f.is_dir[]]
print[f"pathlib.iterdir\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_os_listdir[]:
a = time.time_ns[]
for i in range[RUNS]:
dirname = Path[directory]
fu = [os.path.join[directory, o] for o in os.listdir[directory] if os.path.isdir[os.path.join[directory, o]]]
print[f"os.listdir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_os_scandir[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = [f.path for f in os.scandir[directory] if f.is_dir[]]
print[f"os.scandir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len[fu]}"]
if __name__ == '__main__':
run_os_scandir[]
run_os_walk[]
run_glob[]
run_pathlib_iterdir[]
run_os_listdir[]
8 functions of an
os module to list all files of a directory. Here are the steps.- Nhập mô -đun hệ điều hành
Mô-đun này giúp chúng tôi làm việc với chức năng phụ thuộc hệ điều hành trong Python. Mô -đun OS cung cấp các chức năng để tương tác với hệ điều hành.
- Sử dụng hàm Os.ListDir []
Hàm
9 trả về một danh sách chứa tên của các tệp và thư mục có trong thư mục được đưa ra bởi# -*- coding: utf-8 -*- # Python 3 import time import os from glob import glob from pathlib import Path directory = r"" RUNS = 1 def run_os_walk[]: a = time.time_ns[] for i in range[RUNS]: fu = [x[0] for x in os.walk[directory]] print[f"os.walk\t\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_glob[]: a = time.time_ns[] for i in range[RUNS]: fu = glob[directory + "/*/"] print[f"glob.glob\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_pathlib_iterdir[]: a = time.time_ns[] for i in range[RUNS]: dirname = Path[directory] fu = [f for f in dirname.iterdir[] if f.is_dir[]] print[f"pathlib.iterdir\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_os_listdir[]: a = time.time_ns[] for i in range[RUNS]: dirname = Path[directory] fu = [os.path.join[directory, o] for o in os.listdir[directory] if os.path.isdir[os.path.join[directory, o]]] print[f"os.listdir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"] def run_os_scandir[]: a = time.time_ns[] for i in range[RUNS]: fu = [f.path for f in os.scandir[directory] if f.is_dir[]] print[f"os.scandir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len[fu]}"] if __name__ == '__main__': run_os_scandir[] run_os_walk[] run_glob[] run_pathlib_iterdir[] run_os_listdir[]
0.import os # folder path dir_path = r'E:\\account\\' # list to store files res = [] # Iterate directory for path in os.listdir[dir_path]: # check if current path is a file if os.path.isfile[os.path.join[dir_path, path]]: res.append[path] print[res]
- Lặp lại kết quả
Sử dụng cho vòng lặp để lặp lại các tệp được trả về bởi hàm listDIR []. Sử dụng cho vòng lặp, chúng tôi sẽ lặp lại mỗi tệp được trả về bởi
1Functionimport os # folder path dir_path = r'E:\\account\\' # list to store files res = [] # Iterate directory for path in os.listdir[dir_path]: # check if current path is a file if os.path.isfile[os.path.join[dir_path, path]]: res.append[path] print[res]
- Sử dụng hàm isfile []
Trong mỗi lần lặp vòng lặp, sử dụng hàm
2 để kiểm tra xem đường dẫn hiện tại có phải là tệp hoặc thư mục hay không. Nếu đó là một tập tin, sau đó thêm nó vào một danh sách. Hàm này trả về true nếu một đường dẫn nhất định là một tệp. Nếu không, nó trả về sai.import os # folder path dir_path = r'E:\\account\\' # list to store files res = [] # Iterate directory for path in os.listdir[dir_path]: # check if current path is a file if os.path.isfile[os.path.join[dir_path, path]]: res.append[path] print[res]
Ví dụ để liệt kê các tệp của một thư mục
Hãy để xem cách liệt kê các tệp của một thư mục tài khoản.
# -*- coding: utf-8 -*-
# Python 3
import time
import os
from glob import glob
from pathlib import Path
directory = r""
RUNS = 1
def run_os_walk[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = [x[0] for x in os.walk[directory]]
print[f"os.walk\t\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_glob[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = glob[directory + "/*/"]
print[f"glob.glob\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_pathlib_iterdir[]:
a = time.time_ns[]
for i in range[RUNS]:
dirname = Path[directory]
fu = [f for f in dirname.iterdir[] if f.is_dir[]]
print[f"pathlib.iterdir\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_os_listdir[]:
a = time.time_ns[]
for i in range[RUNS]:
dirname = Path[directory]
fu = [os.path.join[directory, o] for o in os.listdir[directory] if os.path.isdir[os.path.join[directory, o]]]
print[f"os.listdir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]
def run_os_scandir[]:
a = time.time_ns[]
for i in range[RUNS]:
fu = [f.path for f in os.scandir[directory] if f.is_dir[]]
print[f"os.scandir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len[fu]}"]
if __name__ == '__main__':
run_os_scandir[]
run_os_walk[]
run_glob[]
run_pathlib_iterdir[]
run_os_listdir[]
7 sẽ chỉ liệt kê các tệp trong thư mục hiện tại và bỏ qua các thư mục con.list files only in the current directory and ignore the subdirectories.Ví dụ 1: Chỉ liệt kê các tệp từ thư mục: List only files from a directory
import os
# folder path
dir_path = r'E:\\account\\'
# list to store files
res = []
# Iterate directory
for path in os.listdir[dir_path]:
# check if current path is a file
if os.path.isfile[os.path.join[dir_path, path]]:
res.append[path]
print[res]
Output::
Ở đây chúng tôi có ba tên tập tin.
['profit.txt', 'sales.txt', 'sample.txt']
Nếu bạn biết biểu thức máy phát, bạn có thể làm cho mã nhỏ hơn và đơn giản bằng cách sử dụng hàm máy phát như hình bên dưới.
Biểu thức của máy phát::
import os
def get_files[path]:
for file in os.listdir[path]:
if os.path.isfile[os.path.join[path, file]]:
yield file
Sau đó, chỉ cần gọi nó bất cứ khi nào cần thiết.
for file in get_files[r'E:\\account\\']:
print[file]
Ví dụ 2: Liệt kê cả tệp và thư mục.: List both files and directories.
Trực tiếp gọi chức năng
import os
# folder path
dir_path = r'E:\\account\\'
# list to store files
res = []
# Iterate directory
for path in os.listdir[dir_path]:
# check if current path is a file
if os.path.isfile[os.path.join[dir_path, path]]:
res.append[path]
print[res]
4 để có được nội dung của một thư mục.import os
# folder path
dir_path = r'E:\\account\\'
# list file and directories
res = os.listdir[dir_path]
print[res]
Output::
Như bạn có thể thấy trong đầu ra, ‘Báo cáo_2021 là một thư mục.
['profit.txt', 'reports_2021', 'sales.txt', 'sample.txt']
import os
# folder path
dir_path = r'E:\\account\\'
# list to store files
res = []
# Iterate directory
for path in os.listdir[dir_path]:
# check if current path is a file
if os.path.isfile[os.path.join[dir_path, path]]:
res.append[path]
print[res]
5 để liệt kê tất cả các tệp trong thư mục và thư mục con
import os
# folder path
dir_path = r'E:\\account\\'
# list to store files
res = []
# Iterate directory
for path in os.listdir[dir_path]:
# check if current path is a file
if os.path.isfile[os.path.join[dir_path, path]]:
res.append[path]
print[res]
Hàm os.walk [] trả về một trình tạo tạo một bộ giá trị [current_path, thư mục trong current_path, file in current_path].
Lưu ý: Sử dụng chức năng
5, chúng tôi có thể liệt kê tất cả các thư mục, thư mục con và tệp trong một thư mục nhất định.: Using the import os
# folder path
dir_path = r'E:\\account\\'
# list to store files
res = []
# Iterate directory
for path in os.listdir[dir_path]:
# check if current path is a file
if os.path.isfile[os.path.join[dir_path, path]]:
res.append[path]
print[res]
import os
# folder path
dir_path = r'E:\\account\\'
# list to store files
res = []
# Iterate directory
for path in os.listdir[dir_path]:
# check if current path is a file
if os.path.isfile[os.path.join[dir_path, path]]:
res.append[path]
print[res]
5 function we can list all directories, subdirectories, and files in a given directory.Đó là một hàm đệ quy, tức là mỗi khi trình tạo được gọi, nó sẽ theo từng thư mục đệ quy để có được danh sách các tệp và thư mục cho đến khi không có các thư mục phụ nào có sẵn từ thư mục ban đầu.recursive function, i.e., every time the generator is called, it will follow each directory recursively to get a list of files and directories until no further sub-directories are available from the initial directory.
Ví dụ: gọi
import os
# folder path
dir_path = r'E:\\account\\'
# list to store files
res = []
# Iterate directory
for path in os.listdir[dir_path]:
# check if current path is a file
if os.path.isfile[os.path.join[dir_path, path]]:
res.append[path]
print[res]
7 sẽ mang lại hai danh sách cho mỗi thư mục mà nó truy cập. Danh sách đầu tiên chứa các tập tin và danh sách thứ hai bao gồm các thư mục.Hãy cùng xem ví dụ để liệt kê tất cả các tệp trong thư mục và thư mục con.
Example::
def fast_scandir[dirname]:
subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
for dirname in list[subfolders]:
subfolders.extend[fast_scandir[dirname]]
return subfolders
0Output::
def fast_scandir[dirname]:
subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
for dirname in list[subfolders]:
subfolders.extend[fast_scandir[dirname]]
return subfolders
1Lưu ý: Thêm Break Inside một vòng lặp để ngừng tìm kiếm các tệp đệ quy bên trong các thư mục con.: Add break inside a loop to stop looking for files recursively inside subdirectories.
Example::
def fast_scandir[dirname]:
subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
for dirname in list[subfolders]:
subfolders.extend[fast_scandir[dirname]]
return subfolders
2import os
# folder path
dir_path = r'E:\\account\\'
# list to store files
res = []
# Iterate directory
for path in os.listdir[dir_path]:
# check if current path is a file
if os.path.isfile[os.path.join[dir_path, path]]:
res.append[path]
print[res]
8 để lấy các tệp của một thư mục
import os
# folder path
dir_path = r'E:\\account\\'
# list to store files
res = []
# Iterate directory
for path in os.listdir[dir_path]:
# check if current path is a file
if os.path.isfile[os.path.join[dir_path, path]]:
res.append[path]
print[res]
Hàm
import os
# folder path
dir_path = r'E:\\account\\'
# list to store files
res = []
# Iterate directory
for path in os.listdir[dir_path]:
# check if current path is a file
if os.path.isfile[os.path.join[dir_path, path]]:
res.append[path]
print[res]
9 trả về các mục nhập thư mục cùng với thông tin thuộc tính tệp, mang lại hiệu suất tốt hơn cho nhiều trường hợp sử dụng phổ biến.Nó trả về một trình lặp của các đối tượng
['profit.txt', 'sales.txt', 'sample.txt']0, chứa tên tệp.
Example::
def fast_scandir[dirname]:
subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
for dirname in list[subfolders]:
subfolders.extend[fast_scandir[dirname]]
return subfolders
3Output::
def fast_scandir[dirname]:
subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
for dirname in list[subfolders]:
subfolders.extend[fast_scandir[dirname]]
return subfolders
4Mô -đun toàn cầu để liệt kê các tệp của một thư mục
Mô -đun Glob Python, một phần của thư viện tiêu chuẩn Python, được sử dụng để & nbsp; tìm các tệp và thư mục có tên theo một mẫu cụ thể.find the files and folders whose names follow a specific pattern.
Ví dụ: để có được tất cả các tệp của một thư mục, chúng tôi sẽ sử dụng mẫu
['profit.txt', 'sales.txt', 'sample.txt']1. Ở đây,
['profit.txt', 'sales.txt', 'sample.txt']2 có nghĩa là tệp với bất kỳ tiện ích mở rộng nào.
Đọc thêm: Các tệp danh sách Python trong một thư mục với TXT mở rộng.: Python list files in a directory with extension txt.
Hãy để xem cách liệt kê các tệp từ một thư mục bằng mô -đun GLOB.
Example::
def fast_scandir[dirname]:
subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
for dirname in list[subfolders]:
subfolders.extend[fast_scandir[dirname]]
return subfolders
5Output::
def fast_scandir[dirname]:
subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
for dirname in list[subfolders]:
subfolders.extend[fast_scandir[dirname]]
return subfolders
6Lưu ý: Nếu bạn muốn liệt kê các tệp từ các thư mục con, thì hãy đặt thuộc tính ['profit.txt', 'sales.txt', 'sample.txt']
3 thành true.: If you want to list files from
subdirectories, then set the
['profit.txt', 'sales.txt', 'sample.txt']3 attribute to True.
Example::
def fast_scandir[dirname]:
subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
for dirname in list[subfolders]:
subfolders.extend[fast_scandir[dirname]]
return subfolders
7Output::
def fast_scandir[dirname]:
subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
for dirname in list[subfolders]:
subfolders.extend[fast_scandir[dirname]]
return subfolders
8Mô -đun Pathlib để liệt kê các tệp của một thư mục
Từ Python 3.4 trở đi, chúng ta có thể sử dụng mô -đun & nbsp; pathlib, cung cấp trình bao bọc cho hầu hết các chức năng HĐH.
- Nhập mô -đun Pathlib: Mô -đun PathLib cung cấp các lớp và phương thức để xử lý các đường dẫn hệ thống tệp và nhận dữ liệu liên quan đến các tệp cho các hệ điều hành khác nhau.
- Tiếp theo, sử dụng & nbsp; ________ 54 để xây dựng đường dẫn thư mục
- Tiếp theo, sử dụng
['profit.txt', 'sales.txt', 'sample.txt']
5 để lặp lại tất cả các mục của thư mục - Cuối cùng, kiểm tra xem mục nhập hiện tại có phải là tệp sử dụng hàm
['profit.txt', 'sales.txt', 'sample.txt']
6 không
Example::
def fast_scandir[dirname]:
subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
for dirname in list[subfolders]:
subfolders.extend[fast_scandir[dirname]]
return subfolders
9