3

Hello i have a problem finding and opening files in a subdirectory. I have several different files called for example :
mouse_1_animal.txt
mouse_2_animal.txt mouse_3_animal.txt

so i want to find all these files in the subdirectory of the working dir and open them and do something with there lines. This is my try:

i=1
for path, subdirs, files in os.walk(root) :
    for file in files :
        if file == "mouse_{0}_animal.txt".format(i) :
            #do something
            i = i + 1

but apparently it doesn't find all the files so i'm wondering if it's the way i'm using to find the file that is wrong.

steT
  • 99
  • 1
  • 9
  • I'd suggest to get a list of all files which match the pattern and then open them, edit and close one by one. – Igor Apr 09 '15 at 09:55
  • 1
    It may be easier to use `os.listdir()` in case of a single subdirectory. –  Apr 09 '15 at 09:55
  • Note that `files` contains the filenames relative to the current `path` where `os.walk` is at that moment; so you'll need to concatenate the directory and file name (`os.path.join()`) to get the full path name. –  Apr 09 '15 at 09:58
  • http://stackoverflow.com/questions/14798220/how-can-i-search-sub-folders-using-glob-glob-module-in-python – Christian K. Apr 09 '15 at 09:59

4 Answers4

8

The pythonic way:

import glob
for f in glob.glob('./subDir/mouse_*_animal.txt'):
    # do_something
emvee
  • 4,371
  • 23
  • 23
0
import fnmatch
import os
src = 'sourceDirPath'
for root, dirnames, filenames in os.walk(src):
  for filename in fnmatch.filter(filenames, 'mouse*.txt'):
      #do something
        i = i + 1

for older python version you might want to try glob instead of fnmatch

e_i_pi
  • 4,590
  • 4
  • 27
  • 45
kewlkiev
  • 113
  • 1
  • 2
  • 9
0

ok i've solvd my problem like this

 file_list = []
 for name in glob.glob('./subDir/mouse_*_animal.txt'):
    file_list.append(name)
 for i in range(len(file_list)+1):
     if './subDir/mouse_*_animal.txt'.format(i) in file_list:
        #do something 
steT
  • 99
  • 1
  • 9
  • 1
    `glob.glob()` already returns a list of filenames. So you should shorten your code to: `for f in glob.glob('./subDir/mouse_*_animal.txt'): do_something(f)` – emvee Apr 09 '15 at 12:47
0

I would propose something like this. Create a list of strings from files, join them together and write.

import glob


def read_file(filename):
    with open(filename) as f:
        return f.read()


data = [read_file(f) for f in glob.glob('file*.txt')]
conc = "\n>>>>>>>\n".join(data)
with open('output', 'w') as f:
    f.write(conc)
Tomasz Kalisiak
  • 101
  • 2
  • 7