1

In order to open all the files in a specific directory (path). I use the following code:

for filename in os.listdir(path):  # For each file inside path              
     with open(path + filename, 'r') as xml_file:
          #Do some stuff

However, I want to read the files in the directory starting from a specific position. For instance, if the directory contains the files f1.xml, f2.xml, f3.xml, ... ,f10.xml in this order, how can I read all the files starting from f3.xml (and ignore f1.xml and f2.xml) ?

Nelewout
  • 6,281
  • 3
  • 29
  • 39
Xu Liu
  • 13
  • 2
  • 1
    `os.listdir` returns a list of filenames. you can sort lists using `.sort()`. you can search an item in a list and get it's index using `some_list.index("some value")`. you can slice a list to start from a specific index like `for item in some_list[5:]`. Try if that helps! – Felk Jul 25 '19 at 15:39

1 Answers1

2

Straightforward way

import os

keep = False
first = 'f3.xml'

for filename in os.listdir(path):  # For each file inside path
     keep = keep or filename == first
     if keep:
         with open(path + filename, 'r') as xml_file:
             #Do some stuff
Deepstop
  • 3,627
  • 2
  • 8
  • 21