Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (19.9k points)

I have a one folder, within it contains 5 sub-folders. Each sub folder contains some 'x.txt','y.txt' and 'z.txt' files and it repeats in every sub-folders Now I need to read and print only 'y.txt' file from all sub-folders. My problem is I'm unable to read and print 'y.txt' files. Can you tell me how solve this problem.

Below is my code which I have written for reading y.txt file

import os, sys

import pandas as pd

file_path = ('/Users/Naga/Desktop/Python/Data')

for root, dirs, files in os.walk(file_path):    

    for name in files:       

       print(os.path.join(root, name))

       pd.read_csv('TextInformation.txt',delimiter=";", names = ['Name', 'Value'])

error :File TextInformation.txt does not exist: 'TextInformation.txt'

1 Answer

0 votes
by (25.1k points)

You can use the following code to fetch all y.txt files from your subdirectories:

import glob

import pandas as pd


# get all y.txt files from all subdirectories

all_files = glob.glob('/Users/Naga/Desktop/Python/Data/*/y.txt')


for file in all_files:

data_from_this_file = pd.read_csv(file, sep=" ", names = ['Name', 'Value'])

    # do something with the data

Related questions

Browse Categories