Home > Backend Development > Python Tutorial > How to read all files in a folder in python

How to read all files in a folder in python

王林
Release: 2024-03-01 13:19:29
forward
603 people have browsed it

How to read all files in a folder in python

You can use the listdir function of the os module to list all the files in the folder, and then use a loop to read the files one by one.

The following is a sample code:

import os

folder_path = '/path/to/folder'

# 列出文件夹下的所有文件
file_list = os.listdir(folder_path)

# 循环读取文件
for file_name in file_list:
file_path = os.path.join(folder_path, file_name)
if os.path.isfile(file_path):
with open(file_path, 'r') as file:
# 在这里对文件进行处理
# 例如打印文件内容
print(file.read())
Copy after login

Please replace /path/to/folder with the actual path of the folder you want to read.

The above is the detailed content of How to read all files in a folder in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:lsjlt.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template