1

I want to copy only first 50 files. I know how to copy the files but how do I copy only first 50 files? This is the code I'm using for copying the file. It copies all the files present in the folder. I want to copy only first 50 files.

import sys, os, time, shutil
print time.ctime()
path = "C:\\temp"
files = os.listdir(path)
print len(files)
if len(files)<=0:
   print'No Files Present'
else:
   files.sort()
   fileobj = open("log.txt",'a')
   for eachfilename in files:
      src = path+'\\'+eachfilename
      temp = "C:\\Backup\\" +eachfilename
      dst = "C:\\Dest\\" +eachfilename
      shutil.copy(src,temp)
      retrn_val = shutil.move(src, dst)
      print retrn_val
      print "File moved:",eachfilename 
      if retrn_val:
         fileobj.write(eachfilename+','+'moved Sucessfully'+'\n')
      else:
         fileobj.write(eachfilename+','+'failed to move'+'\n')

print time.ctime()

Is there any function to specify number of files to copy?

heycooldude
  • 321
  • 2
  • 5
  • 12
  • I'm a newbie to python, that's why so silly question – heycooldude Oct 30 '13 at 06:31
  • @AndreasJung flagging for useless comment and downvote. Try to be more accommodating in your life and lets make SO welcoming to beginners and advanced players alike. – deadcode Aug 22 '18 at 11:52

1 Answers1

3

You could replace

files = os.listdir(path)

with

files = os.listdir(path)[:50]

This would slice the list and limit the number of files to 50.

Community
  • 1
  • 1
miku
  • 181,842
  • 47
  • 306
  • 310
  • +1 this is pretty much the answer. alternative, I was going to suggest: `for eachfilename in files[:50]` If the OP wanted to know the total number of files, but only wanted to iterate of the first 50. –  Oct 30 '13 at 05:55
  • Thanks alot. I'm a newbie to python, that's why so silly question. – heycooldude Oct 30 '13 at 06:21