0
Follow
4
View

How does python traverse files in the current directory?(no recursion)

cruff05 注册会员
2023-02-28 10:24

the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ. < br / > you can use OS listdir() function to traverse the current directory files, do not need the recursive traversal subdirectory. This function returns a list of the names of all files and subdirectories in the specified directory.

For example, the following code lists all files and subdirectories in the current directory:
import os

current_dir = '.'  # 当前目录
for filename in os.listdir(current_dir):
    path = os.path.join(current_dir, filename)
    if os.path.isfile(path):
        print('File:', filename)
    elif os.path.isdir(path):
        print('Directory:', filename)


In the above code, you first use the os.listdir() function to get a list of the names of all the files and subdirectories in the current directory. Then, use the os.path.join() function to concatenate the directory and file names into a full path. Next, the os.path.isfile() and os.path.isdir() functions are used to determine whether the path corresponds to a file or a subdirectory and process accordingly.

panchaoyu1 注册会员
2023-02-28 10:24

If you have any help please accept, thank you


#!/usr/bin/python3
# -*- coding: utf-8 -*-
# 2023-02-28

import os 
from os import path 

current_dir=f'G:\\test'

file  = os.listdir(current_dir)
for f in file:
        real_url = path.join (current_dir , f)
        if path.isfile(real_url): # 输出文件路径
            print(path.abspath(real_url))
        elif path.isdir(real_url): # 输出文件夹路径
            print(real_url)
        else:
            print("既不是文件夹和文件的情况,跳过")
            pass
        

img

lucky_xu123 注册会员
2023-02-28 10:24
import os
for n in os.listdir(current_dir):
        print(n)

Helpful, hope to adopt