python怎么读取文件夹中的文件

26次阅读
没有评论

共计 543 个字符,预计需要花费 2 分钟才能阅读完成。

读取文件夹中的文件可以使用 Python 的 os 模块和 glob 模块。以下是两种常用的方法:

方法一:使用 os 模块的 listdir 函数

import os

folder_path = ' 文件夹路径 '
for filename in os.listdir(folder_path):
    file_path = os.path.join(folder_path, filename)
    if os.path.isfile(file_path):
        with open(file_path, 'r') as file:
            # 处理文件内容 
            pass

方法二:使用 glob 模块的 glob 函数

import glob

folder_path = ' 文件夹路径 '
file_list = glob.glob(folder_path + '/*')
for file_path in file_list:
    if os.path.isfile(file_path):
        with open(file_path, 'r') as file:
            # 处理文件内容 
            pass

以上代码中,需要将’文件夹路径’替换为实际的文件夹路径。然后遍历文件夹中的文件,使用 open 函数打开文件并进行处理。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-16发表,共计543字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)