Python - WindowsError: [Error 2] The system cannot find the file specified

前端 未结 4 1652
梦毁少年i
梦毁少年i 2020-12-21 19:49

I have a folder full of pdf files. I\'m trying to remove all the spaces from files name and replace them with underscores. Here\'s what I have so far:

import         


        
相关标签:
4条回答
  • 2020-12-21 19:53

    just change your directory to the one in which the files has to be renamed and then follow your code.

    use: os.chdir("destinationFolder").

    0 讨论(0)
  • 2020-12-21 19:56

    You renaming files in current directory but reading in the folder. You need to add to os.rename the folder path or at the beginning os.chdir(folder) and then just use os.listdir() and os.rename

    0 讨论(0)
  • 2020-12-21 19:59

    ...

    os.rename(os.path.join(folder, files), os.path.join(folder, NewName))
    
    0 讨论(0)
  • 2020-12-21 20:07

    I found a simple solution for my case. I was wanting to rename files and kept getting the WindowsError: [Error 2]. Simply changing the current directory with

    os.chdir(currdir)
    

    and then not trying to work with the full path did the trick. Here's the relevant lines of script

    if(os.path.exists(wd)) == 0:
    print(wd+" DOES NOT EXIST!!")
    sys.exit()
    
    directories = [x[0] for x in os.walk(wd)]
    ld = len(directories)
    dsorted = sorted(directories)
    print(dsorted)
    
    for num in range(1,ld):
        currdir = dsorted[num]
        print("Working on Directory  "+currdir)
        os.chdir(currdir)
        filenames = next(os.walk(currdir))[2]
        l = len(filenames)
    
        for num in range(0,l):
    
            name = filenames[num]
            print("Present file  "+name)
            modtime = os.path.getmtime(name);print(modtime)
            moddate =datetime.datetime.fromtimestamp(modtime).strftime('%Y %m %d')
            moddate = moddate.replace(" ", "")
            print(moddate)
    
            namesplit = name.split(".")
    
            base = namesplit[0]
            newbase = base+"_"+moddate   
            newname = newbase+"."+namesplit[1]
            print(newname)       
    
            os.rename(name,newname)
            input()
    
    0 讨论(0)
提交回复
热议问题