简体   繁体   English

os.rename()文件到文件夹名称的一部分

[英]os.rename() file to part of folder name

I have multiple folders that look like folder.0 and folder.1 . 我有多个文件夹,看起来像folder.0folder.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. 在每个文件夹中都有一个文件( 'junk' )我要复制并重命名为它当前所在的文件夹名称的.0.1部分。
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. 我甚至不确定我应该使用os.rename。 I just want to pull out files == 'junk' and copy them to one directory but they all have the exact same name. 我只想提取files == 'junk'并将它们复制到一个目录,但它们都具有完全相同的名称。 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(). 您需要提供完整的相对或绝对路径作为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. 注意:目标目录应该已经存在,或者您将需要代码来创建它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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