重命名具有一级子文件夹名称的文件

时间:2017-07-16 14:31:20

标签: python python-2.7 rename

我有一个父文件夹和几个子文件夹

parent:
--subfolder1:
-----folderinsidesubfolder1:
-------file.tsv
--subfolder2:
-----folderinsidesubfolder2:
-------file.tsv

我要做的是将file.tsv更改为文件夹名称一级以上是subfolder1,subfolder2就像这样

parent:
    --subfolder1:
    -----folderinsidesubfolder1:
    -------subfolder1.tsv
    --subfolder2:
    -----folderinsidesubfolder2:
    -------subfolder2.tsv

代码:

from os import walk, path, rename
for dirpath, _, files in walk('pathto/parent'):
    for f in files:
        if f.endswith(".tsv"):
           print rename(f, dirpath[-2]+ '.tsv')

错误:

OSError: [Errno 2] No such file or directory

这是正确的方法吗?

1 个答案:

答案 0 :(得分:1)

os.path.split()创建一个头尾,所以你需要拆分两次以获得祖父目录,例如:

import os
for dirpath, _, files in os.walk('pathto/parent'):
    for f in files:
        if f.endswith('.tsv'):
            os.rename(os.path.join(dirpath, f), os.path.join(dirpath, os.path.split(os.path.split(dirpath)[0])[1] + '.tsv'))