Python: rename a file


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. # simply
  2. import os
  3. os.rename('a.txt','b.kml')
  4.  
  5. # or
  6.  
  7. import shutil
  8. shutil.move('a.txt', 'b.kml')
  9.  
  10.  
  11. # or if you want to copy..
  12.  
  13. import shutil
  14. shutil.copy('a.txt', 'b.kml')
  15.  
  16.  
  17.  
  18.  
  19.  
  20. #
  21. # Another example: I am trying to rename a list of files:
  22. #
  23. # File1.File1
  24. # File2.File2
  25. #
  26. # etc
  27. #
  28. # I need them to be renamed to:
  29. #
  30. # File1
  31. # File2
  32. # etc
  33.  
  34.  
  35.  
  36.  
  37. import os,shutil
  38.  
  39. def renamer(target) :
  40. os.chdir(target)
  41. for filename in os.listdir('.') :
  42. print filename
  43. newfilename = os.path.splitext(filename)[0]
  44. print newfilename
  45. os.rename(filename, newfilename)
  46. print "Renamed " + filename + " to " + new_filename
  47.  
  48. # test the function/module
  49. if __name__ == __main__:
  50. renamer(sys.argv[1])
  51.  
  52.  
  53. # or more simply:

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.