Reputation: 67
My codes work but for a few pain points that perhaps you can help me understand. I want to copy files from one directory to another and rename them at the same time. for example:
c:\path\
octo.jpeg
novem.jpeg
decem.jpeg
to:
c:\newpath\
001.jpeg
002.jpeg
003.jpeg
The codes I wrote from a cursory google search are as follows but I'm not sure why I need the 'r' in the path variables. The 'files = os.listdir(srcPath)' line I'm sure I don't need. This will move the files and renames them using the 'count' variable in the for loop but I want to name each file starting at a specific number, say 65. Should I use the shutil library and copy2 method to first copy the files and then rename or is there an easier way?
import os
from os import path
srcPath = r'C:\Users\Talyn\Desktop\New folder\Keep\New folder'
destPath = r'C:\Users\Talyn\Desktop\New folder\Keep\hold'
#files = os.listdir(srcPath)
def main():
for count, filename in enumerate(os.listdir(srcPath)):
dst = '{:03d}'.format(count) + ".jpeg"
os.rename(os.path.join(srcPath, filename), os.path.join(destPath, dst))
if __name__=="__main__":
main()
Upvotes: 1
Views: 238
Reputation: 893
From the official Python Docs:
Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters.
The r
is telling python interpreter to treat the backslashes(\
) in the path string as literal characters and not as escaping characters.
For naming the files from a specific number:
dst = '{:03d}'.format(count + your_number) + ".jpeg"
Using copyfile
from shutil
copyfile(srcPath + filename, destPath + dst)
Upvotes: 1