Adii
Adii

Reputation: 43

Get path of all .txt files in a folder and subfolders

I have to get path of all files from a folder, with a specific extension, let's say .txt ( I thing it's the same for another extension) and put them in a .txt file. The problem is that in the folder, are others folders with other .txt files, and I need the path from them too. I wrote a code, but it's not working for subfolders. Can anybody help?

list1=[]; 

outputFilePath = 'C:\...\playlist.txt'

with open("C:\\...\\folderPath2.txt","r") as f:
    output = f.readline()


for dir_, _, files in os.walk(output):
    for fileName in files:
                relDir = os.path.abspath(output)
                relFile = os.path.join(relDir, fileName)
                list1.append(relFile)   


with open(outputFilePath, 'r+') as file1:
         for lines in list1:
            file_name, file_extension = os.path.splitext(lines)
            if  (file_extension == '.txt'):
                file1.writelines(lines)
                file1.writelines('\n')

Upvotes: 3

Views: 3333

Answers (3)

Martin Evans
Martin Evans

Reputation: 46759

This will write all of the .txt files to a file_list.txt file with the full path.

import fnmatch
import os

output_file_path = 'file_list.txt'
folder_root = r'e:\myfiles' 

with open(output_file_path, 'w') as f_output:
    for root, dirnames, filenames in os.walk(folder_root):
        for filename in fnmatch.filter(filenames, '*.txt'):
            f_output.write(os.path.join(root, filename)+'\n')

Upvotes: 0

AChampion
AChampion

Reputation: 30258

You can use fnmatch.filter and unix style globbing patterns:

import fnmatch
import os
barlist = []
for root, dirnames, filenames in os.walk('src'):
    for filename in fnmatch.filter(filenames, '*.txt'):
        barlist.append(os.path.join(root, filename))

Upvotes: 3

Logan Jones
Logan Jones

Reputation: 324

I would do something along these lines:

from os import walk
from os.path import splitext
from os.path import join

foodir = r"C:\path\to\top\dir"
barlist = list()

for root, dirs, files in walk(foodir):
  for f in files:
    if splitext(f)[1].lower() == ".txt":
      barlist.append(join(root, f))

Then you can process barlist however you want. There might be a better way of doing it, but that's what I came up with off the top of my head.

Upvotes: 3

Related Questions