-1

I'm looking to rename files from a USB drive with this script but my src variable isn't working right

I've tried removing the 'E:\SC-102818' from src but it never works

import os

def main():
    i = 0

    for filename in os.listdir("E:\SC-102818"):
        dst ="SCF" + str(i) + ".jpg"
        src ='E:\SC-102818' + filename

        os.rename(src, dst)
        i += 1

if __name__ == '__main__':

    main()

I expect it to execute properly but it spits out a FileNotFoundError. When I look at it, the beginning portion of the file it's searching for has E:\SC-102818 at the front.

LukeF9
  • 1
  • 3

1 Answers1

0

Simply change src = 'E:\SC-102818' + filename to src = r'E:\SC-102818\' + filename The backslash needs to be escaped so the string is turned into a raw string. There also needs to be a slash before the filename so it can show up as a file of the directory SC-102818. The current output is instead SC-102818filename instead of SC-102818\filename.

dst also needs to be changed else the file will just be moved to the current directory. That can be done similarly to what you did with src, dst = r'E:\SC-102818\' + "SCF" + str(i) + ".jpg"

SuperDyl
  • 40
  • 1
  • 8
  • That dst part is wrong because then it changes what the final name of the file ends up as. And adding in the backslash after the '...-102818' just goes in and causes a syntax error – LukeF9 Jan 05 '19 at 07:20
  • The syntax error is because the string needs to appended with 'r', `r'E:\SC-102818\'`. Alternatively, you can use double backslashes: `'E:\\SC-102818\\'`. Adding `r'E:\SC-102818\'` to `dst` is important because renaming a file also moves it. Without this path, the file will be renamed and moved to the working directory. If you want to rename the files without moving them, you need to specify the full path in the new file name. – SuperDyl Jan 05 '19 at 17:48
  • Thank you! Your solution was what I needed. – LukeF9 Jan 05 '19 at 19:19