简体   繁体   中英

os.rename() can't find specified file(s)

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM