简体   繁体   English

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

[英]Trying to reach all .txt files in Python

I have a folder which is "labels". 我有一个名为“标签”的文件夹。 In this folder, thera are 50 folders again and each of these 50 folder have .txt files. 在此文件夹中,thera再次是50个文件夹,这50个文件夹中的每个文件夹都有.txt文件。 How can I reach these .txt files with using Python 2? 如何使用Python 2访问这些.txt文件?

Here's code that will go through all folders in labels and print content of txt files located inside them. 这里的代码将遍历标签中的所有文件夹并打印其中的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)

If you just want to list the files in the folders: 如果只想列出文件夹中的文件:

import os


rootdir = 'C:/Users/youruser/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print (os.path.join(subdir, file))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM