Six ways for Python to get all files in the current directory

The listdir() function in the os module

import os

# 当前目录
dir_path = '/path/to/current/directory'

# 获取当前目录下的所有文件
files = [os.path.join(base_dir, file) for file in os.listdir(base_dir)]

# 遍历文件列表,输出文件名
for file in files:
    print(file)

In this code, os.listdir()the method returns a list because the file name is obtained, not the file path. If you need to get the file path, you can use os.path.join()the method to concatenate the file names in the list into a complete path.

The glob() function in the glob module

import os
import glob

# 获取当前目录
directory = os.getcwd()

# 获取所有文件
files = glob.glob(directory + "/*")

# 输出所有文件名
for file in files:
    print(file)

In this code, os.getcwd()the current working directory is returned. glob.glob()The function is used to get all the files in the specified directory, including files and directories. Note the asterisk . Finally, use a for loop to iterate through all file names and output them.

The walk() function in the os module

import os

dir_path = '当前目录'
for dirpath, dirnames, filenames in os.walk(dir_path):
    for filename in filenames:
        if filename == '需要获取的文件名字':
            print(os.path.join(dirpath, filename))

Use the walk() function in the os module to recursively traverse all files and folders in the current directory, and filter out the required files through the filter function.

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())

Use the read_csv() function in the pandas library

import pandas as pd

# 当前目录下所有文件的路径
file_paths = ['.']

# 获取所有文件的数据并转换为pandas的DataFrame
df = pd.read_csv(file_paths)

# 打印DataFrame中的内容
print(df)

osqp

import osqp

# 当前目录
base_dir = '.'

# 获取当前目录下所有文件
files = osqp.find_files(base_dir)

# 打印文件列表
for file in files:
    print(file)

Guess you like

Origin blog.csdn.net/lilongsy/article/details/131044866