gpt4 book ai didi

python - 尝试在 Python 中访问所有 .txt 文件

转载 作者:行者123 更新时间:2023-12-01 01:26:42 24 4
gpt4 key购买 nike

我有一个名为“labels”的文件夹。在这个文件夹中,又有 50 个文件夹,这 50 个文件夹中的每一个都有 .txt 文件。如何使用 Python 2 访问这些 .txt 文件?

最佳答案

下面的代码将遍历标签中的所有文件夹并打印其中的 txt 文件的内容。

import os

for folder in os.listdir('labels'):
for txt_file in os.listdir('labels/{}'.format(folder)):
if txt_file.endswith('.txt'):
file = open('labels/{}/{}'.format(folder, txt_file), 'r')
content = file.read()
file.close()

print(content)

关于python - 尝试在 Python 中访问所有 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53267249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com