How to skip first few files when looping using os.listdir(path)?

Tags:



I am using os.listdir(path), However, I want to skip the first few files available in the path.

for file in os.listdir(local_path):
    with open(os.path.join(local_path, file)) as myfile:
    # This will open all the files 

ALL THE FILES IN PATH ARE NAMED AND SORTED. For example, file0000, file0001, file0002 ..etc What I can use to skip say first 5 files and use the rest of other files.

Answer

os.listdir doesn’t guarantee order, so you should sort first to make sure, then you can just slice:

for file in sorted(os.listdir(local_path))[5:]:
    # rest of the code goes here


Source: stackoverflow