Bootstrap

【Python】获取文件夹下所有文件

1、os

import os

# 不含子文件夹
def get_files(path):
	files = [os.path.join(base_dir, file) for file in os.listdir(base_dir)]
	for file in files:
        if os.path.isfile(file):
            print(file)

# 含子文件夹
def get_files_all(path):
    for root, dirs, files in os.walk(path):
        level = root.replace(path, '').count(os.sep)
        indent = ' ' * 4 * level
        print('{}{}/'.format(indent, os.path.basename(root)))
        redundant = ' ' * 4 * (level + 1)
        for f in files:
            print('{}{}'.format(redundant, f))

2、glob

import os
import glob

directory = os.getcwd()
files = glob.glob(directory + "/*")
for file in files:
    print(file)

3、pathlib

from pathlib import Path

# 不含子文件夹
def list_files_in_directory(directory):
    directory_path = Path(directory)
    for file in directory_path.iterdir():
        # 检查是否是文件(排除目录)
        if file.is_file():
            print(file)


list_files_in_directory(r'C:\Users\admin\Desktop\文件夹1')


# 含子文件夹
def list_files(path):
    p = Path(path)
    for file in p.rglob('*'):  # 使用rglob('*')来递归地查找所有文件
        print(file)


# 调用
list_files(r'C:\Users\admin\Desktop\文件夹1')

4、subprocess

import os
dir_path = '当前目录'
files = os.listdir(dir_path)
for file in files:
    output = subprocess.check_output(['ls', '-l', '-a', dir_path, file])
    print(file + ':' + output.decode('utf-8').strip())

5、pandas

import pandas as pd
# 当前目录下所有文件的路径
file_paths = ['.']
# 获取所有文件的数据并转换为pandas的DataFrame
df = pd.read_csv(file_paths)
# 打印DataFrame中的内容
print(df)

6、osqp

import osqp
# 当前目录
base_dir = '.'
# 获取当前目录下所有文件
files = osqp.find_files(base_dir)
# 打印文件列表
for file in files:
    print(file)

10、资料

;