深度阅读

How to read multiple text files from folder in Python?

作者
作者
2023年08月22日
更新时间
10.91 分钟
阅读时间
0
阅读量

To read multiple text files from a folder in Python, you can use the os module to get a list of all files in the specified directory, and then read each file using the built-in open function. Here’s an example:

import os

dir_path = '/path/to/folder'
files = os.listdir(dir_path)

for filename in files:
    if filename.endswith('.txt'):
        file_path = os.path.join(dir_path, filename)
        with open(file_path, 'r') as f:
            text = f.read()
            # Do something with the text

In this example, we first use os.listdir() to get a list of all files in the specified directory. We then loop through each file and check if it ends with the “.txt” extension. If it does, we construct the full file path using os.path.join() and open the file using open() with the ‘r’ mode (for reading). We then read the content of the file using read() and do something with the text.

You can modify this code to suit your specific needs, such as changing the directory path, filtering files by a different extension, or processing the text in a different way.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。