根据文件结构重命名文件

时间:2017-06-27 11:05:31

标签: python-3.x

我有一个包含文件夹和文件的目录结构:

DIR /目录/目录/ file1.jpg
DIR /目录/目录/ file2.jpg
DIR /目录/目录/ file3.jpg
DIR / DIR / DIR / DIR / file1.jpg
DIR / DIR / DIR / DIR / file2.jpg
dir / dir / dir / dir / file3.jpg

我想根据文件夹结构复制和重命名每个图像,所以:

dir_dir_dir_file1.jpg
dir_dir_dir_file2.jpg
dir_dir_dir_file3.jpg

dir_dir_dir_dir_file1.jpg
dir_dir_dir_dir_file2.jpg
dir_dir_dir_dir_file3.jpg

到目前为止,我有这个,但我可以做一些帮助/指针。

import os
import sys

for dirname, dirnames, filenames in 
    os.walk('/Users/Gerrit/Documents/gygaia/Python_scripts/Photos', topdown=True):
    # print path to all subdirectories first.
    for subdirname in dirnames:
        print(os.path.join(dirname, subdirname))

# print path to all filenames.
    for filename in filenames:
        #print(os.path.join(dirname, filename))
        path = os.path.join(dirname, filename)

    #replace path string '/' with '_'
    #replace path string '\' with '_'
    print(path.replace('/', '_')) 

编辑

import os, subprocess
from shutil import copyfile
os.chdir('C:\\Users\Gerrit\Documents\gygaia\Python_scripts\Photos')     
root_dir =  os.getcwd()
def file_mover():
for root, dirs, files in os.walk(os.getcwd()):
    for file in files:
        if file.endswith(".jpg"):
            print(os.path.join(root, file))
            src = (os.path.join(root, file))
            # remove the cwd from the path
            path = src.replace(root_dir, "")
            # replace \\ with _ in the paths
            path = path.replace("\\", "_")
            file_name = path.replace("_", "",1)
            # copy and rename the jpg files including the file path
            os.chdir("..")
            dst = os.getcwd() + "\\Photos_mirror"
            copyfile(src, dst)
file_mover()

旧的EDIITED 我已经设法得到这么远,但复制文件命令不起作用,它说权限错误12,我尝试用管理员权限(Windows)打开python IDE但它仍然无法正常工作,这里是代码:

###Script to copy images and rename them by their former directory location### 

import os, sys, subprocess, glob
from shutil import copyfile

def file_mover():

#First set working directory - we don't want to rename everything!
os.chdir('C:\\Users\Gerrit\Documents\gygaia\Python_scripts\Photos')     
path =  os.getcwd()
print (path)

for dirname, dirnames, filenames in os.walk(path, topdown=True):
# print path to all subdirectories first.
print("loop 1")
for subdirname in dirnames:
    print(os.path.join(dirname, subdirname))
    path2 = (os.path.join(dirname, subdirname))

    # remove the cwd from the path
    path = path2.replace(path, "")

    # replace \\ with _ in the paths
    path = path.replace("\\", "_")
    path = path.replace("_", "",1)
    path = path + ("_")
    print("loop 2")

    # copy and rename the jpg files including the file path
    os.chdir("..")
    dst = os.getcwd() + "\\Photos_mirror"
    src = dirname +("\\")

    copyfile(src, dst)

2 个答案:

答案 0 :(得分:0)

已编辑试试这个:

import os
import shutil

wd = r'C:\Users\Gerrit\Documents\gygaia\Python_scripts\Photos'
def file_mover():
  for path, dirs, files in os.walk(wd):
    for file in files:
      if file.endswith(".jpg"):
        src = os.path.join(path, file)
        #Assuming 'Photos_mirror' folder is in folder which images are located
        dst = os.path.join(os.getcwd(), "Photos_mirror")
        if not os.path.exists(dst): #Checks 'Photos_mirror' folder exists otherwise creates
          os.makedirs(dst)
        new_name = src.replace(wd+'\\', '').replace('\\', '_')
        new_dst = os.path.join(dst, new_name)
        if not os.path.isfile(new_dst):
          shutil.copy(src, dst)
          old_dst = os.path.join(dst, file)
          #Assuming your /dir/dir/... structure is inside of your working directory (wd)
          os.rename(old_dst, new_dst)
        else:
          continue

file_mover()

如果您有疑问或我误解了您的问题,请随时发表评论

答案 1 :(得分:0)

您可以使用#checkout来简化大部分内容

我无法测试这个,但是这样的事情应该可行

pathlib.Path

在测试成功时删除正确的#