简体   繁体   中英

os.rename() file to part of folder name

I have multiple folders that look like folder.0 and folder.1 . Inside each folder there is one file ( 'junk' ) that I want to copy and rename to the .0 or .1 part of the folder name in which it currently resides.
Here is what I'm trying to do:

inDirec = '/foobar'
outDirec = '/complete/foobar'


for root, dirs,files in os.walk(inDirec):
    for file in files:
        if file =='junk'
            d = os.path.split(root)[1]
            filename, iterator = os.path.splitext(d)  # folder no. captured
            os.rename(file, iterator+file) # change name to include folder no.
            fullpath = os.path.join(root,file)
            shutil.copy(fullpath,outDirec)

This returns:

os.rename(file,iterator+file)
OSError: [Errno 2] No such file or directory

I'm not even sure I should be using os.rename. I just want to pull out files == 'junk' and copy them to one directory but they all have the exact same name. So I really just need to rename them so they can exist in the same directory. Any help?

Update

    for root, dirs,files in os.walk(inDirec):
    for file in files:
        if file =='junk'
            d = os.path.split(root)[1]
            filename, iterator = os.path.splitext(d)  # folder no. captured
            it = iterator[-1] # iterator began with a '.'

            shutil.copy(os.path.join(root,file),os.path.join(outDirec,it+file))

Your problem is that your program is using the working directory at launch for your rename operation. You need to provide full relative or absolute paths as arguments to os.rename().

Replace:

os.rename(file, iterator+file)
fullpath = os.path.join(root,file)
shutil.copy(fullpath,outDirec)

With (if you want to move):

os.rename(os.path.join(root, file), os.path.join(outDirec, iterator+file))

Or with (if you want to copy):

shutil.copy(os.path.join(root, file), os.path.join(outDirec, iterator+file))

NOTE: The destination directory should already exist or you will need code to create it.

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