1

Using looping as follows to list n files from a directory:

myfiles = glob.glob("*.xml")
files = len(myfiles)

count = 0
myfiles.sort()
files_to_process = 3
for filename in myfiles:
   count += 1
   print (time.strftime("%I:%M:%S"), count ,'of', files, '|', filename)
   if count == files_to_process:
      break

is there an alternative way to iterate only through n times other than using break?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
haz
  • 740
  • 1
  • 11
  • 20

4 Answers4

2
myfiles = glob.glob("*.xml")
files = len(myfiles)

myfiles.sort()
files_to_process = 3

for i in range(min(files_to_process, files)):
  print (time.strftime("%I:%M:%S"), i+1 ,'of', files, '|', myfiles[i])
kg1313
  • 66
  • 5
  • This is a nice clean solution, but it will give an `IndexError` when there are fewer than three files in the list. – kaya3 Dec 11 '19 at 03:13
  • Added in a min() to avoid that IndexError - not quite as clean anymore though :) – kg1313 Dec 11 '19 at 03:22
1

You can take only the first count file names with myfiles[:count] or itertools.islice(myfiles, count).

satoru
  • 31,822
  • 31
  • 91
  • 141
1

Try this:

myfiles = glob.glob("*.xml")
files = len(myfiles)

count = 0
myfiles.sort()
files_to_process = 3
for filename in myfiles[:files_to_process]:
   count += 1
   print (time.strftime("%I:%M:%S"), count ,'of', files, '|', filename)
Paul Whipp
  • 16,028
  • 4
  • 42
  • 54
1

Here's a way using zip: the behaviour is to stop after exhausting whichever sequence is shorter. Zipping with a range also saves you having to manually update a counter.

myfiles = glob.glob("*.xml")
files = len(myfiles)

myfiles.sort()
files_to_process = 3

for filename, count in zip(myfiles, range(1, files_to_process+1)):
    print(time.strftime("%I:%M:%S"), count, 'of', files, '|', filename)

That said, this solution is not idiomatic, and I don't think the code is better than the version using break.

kaya3
  • 47,440
  • 4
  • 68
  • 97