Xu Liu
Xu Liu

Reputation: 13

How to open files in a directory starting from a specific file

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) ?

Upvotes: 1

Views: 509

Answers (1)

Deepstop
Deepstop

Reputation: 3827

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

Upvotes: 2

Related Questions