input - Python changing filenames of multiple files in a folder -
i'm trying make script rename files in folder , code have, doesn't work. have 200 images in folder , want change filename1_ filename1 , on files. transformation dog_1 doggy1; or whatever, new name of file can anything. me out? i'm still new python code have right might nothing.
import os directoryname="c:\\users\\ineke\\documents\\python scripts\\images" lijstmetfiles = os.listdir(directoryname) in range(len(lijstmetfiles)): os.rename(str(lijstmetfiles[i]), str("doggy"+str(i))
i ran code , here 2 main problems:
the first being, not closing bracket on os.rename
line.
you have this:
os.rename(str(lijstmetfiles[i]), str("doggy"+str(i))
you missing parentheses, should be:
os.rename(str(lijstmetfiles[i]), str("doggy"+str(i)))
however, edit issue copying code on in post.
secondly, , importantly, not specifying path want rename on, giving 2 filenames, getting file not found error.
you need make use of python's os.path.join
method using directory , filename, in code sample below:
os.rename( os.path.join(directoryname, str(lijstmetfiles[i])), os.path.join(directoryname, str("doggy"+str(i))) )
so explicitly specifying full path rename.
another point make, don't need casting "str" filenames. if filename 5
example, getting list of files listdir
still come string.
finally, putting together, code should this:
import os directoryname="c:\\users\\ineke\\documents\\python scripts\\images" lijstmetfiles = os.listdir(directoryname) print(lijstmetfiles) in range(len(lijstmetfiles)): os.rename( os.path.join(directoryname, lijstmetfiles[i]), os.path.join(directoryname, "doggy"+str(i)) )
i tested on end , should work.
here documentation on os module. take @ further understanding of available when playing filesystem:
Comments
Post a Comment