【问题标题】:how can I move files into corresponding folders如何将文件移动到相应的文件夹中
【发布时间】:2013-01-28 14:24:09
【问题描述】:

我有一个脚本,该脚本旨在通过查找每个文件的第一个字母然后检查名称的唯一性来创建多个文件夹,然后根据唯一值创建文件夹并在唯一值之后命名文件夹并完成通过将相应的文件放入正确的文件夹中。我的代码是

import os
from os import listdir
import dircache
import sys
import shutil
import dircache
import glob

path = "C:\\Users\\hra\\Desktop\\fg"
dirList=os.listdir(path)
for fname in dirList:
    print fname

#myList = fname
myList2 = sorted(dirList, key=lambda x:x[0:3])
oldList = [x[0] for x in myList2]
newList = list(set(oldList))
for char in newList:
    print newList

root_path = "C:\\Users\\hra\\Desktop\\fg"
folders = newList
for folder in folders:
    os.mkdir(os.path.join(root_path,folder))


fCounter = len(glob.glob1("C:\\Users\\hra\\Desktop\\fg","f*"))
mCounter = len(glob.glob1("C:\\Users\\hra\\Desktop\\fg","m*"))
bCounter = len(glob.glob1("C:\\Users\\hra\\Desktop\\fg","b*"))
nLCounter =  len(newList)

到目前为止,我已经设法让我的代码从唯一值创建和重命名所需的文件,但我正在努力将我的文件移动到相应的文件夹中,因为它意味着能够处理可能无限数量的文件这可能会导致许多独特的价值被创造出来

【问题讨论】:

    标签: python file move directory


    【解决方案1】:

    将其添加到程序的末尾

    import os
    for fname in dirList:
      os.rename(fname,os.path.join(root_path,fname[0],fname))
    

    或者你可能想导入shutil并使用

    shutil.copyfile(fname, path.join(root_path,fname[0],fname))
    

    因为这是非破坏性的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-23
      • 2013-01-15
      • 2017-09-16
      • 2014-02-13
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 2022-12-10
      相关资源
      最近更新 更多