Home python Python script to rename files

Python script to rename files

Author

Date

Category

I need to rename all the photos lying in my folder, on 1.jpg, 2.jpg and so on.

import os
Path = Raw_input ("C: \ Users \ Admin \ APPDATA \ LOCAL \ photo")
ListOffiles = OS.Listdir (Path)
Countoffiles = Len (ListOffiles)
OS.CHDIR (PATH)
For i in Range (0, Countoffiles):
  OS.RENAME (Path + ListOffiles [i], Str (i + 1) + '.jpg')

This script shakes a mistake.


Answer 1, Authority 100%

Try:

import os
Path = R "C: \ Users \ Admin \ APPDATA \ LOCAL \ photo"
i = 1.
FOR FILE_NAME IN OS.LISTDIR (PATH):
  # File name and its format
  Base_Name, Ext = OS.path.splitext (File_Name)
  # Named files of a specific format
  If ext.lower () not in ['.jpg', '.jpeg']:
    Continue.
  # Full path to the current file
  ABS_File_name = Os.path.join (Path, File_Name)
  # Full path to the current file with a new name
  new_abs_file_name = os.path.join (Path, Str (I) + EXT)
  OS.RENAME (ABS_FILE_NAME, new_abs_file_name)
  I + = 1

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions