使用python os库移动特定文件

时间:2015-02-03 16:08:59

标签: python operating-system

我想使用Python os模块将单个文件从一个充满照片的目录移动到新创建的目录。操作系统重命名(https://docs.python.org/2/library/os.html#module-os)似乎很有希望,但它似乎不能一次移动一个文件,而只是重命名整个目录。

for i, v in enumerate(directories):
    newpath = "/Users/simonorlovsky/code/carleton_archive/newsreleaseFolders/directories/"+v
    files = os.listdir( newpath )

    #Check to make sure this directory isn't empy
    if files == []:
        print v, "is empty"
    directories[v] = files
    print "Folder:", v
    print "Files:", directories[v]
    filesToCopyOver = directories[v]
    for i in range(len(filesToCopyOver)):
        filesToCopyOver[i]= filesToCopyOver[i][:-3]+"tiff"
    print "Files to move over", filesToCopyOver
    src = "/Users/simonorlovsky/code/carleton_archive/newsreleaseFolders/tiffs/"
    print "Source:", src
    dst = "/Users/simonorlovsky/code/carleton_archive/newsreleaseFolders/"+v
    print "Destination", dst
    print ""
    os.mkdir(v)
    shutil.move(src, dst)
    print ""

2 个答案:

答案 0 :(得分:2)

我建议你在python中使用shutil库。它有一个“移动”方法。当然,您总是可以查找源代码到shutil.move,看看他们是如何做到的。

答案 1 :(得分:0)

这最终修复了我的代码。对于shutil.move(src,dst),您可以为src放入特定的文件名。在我感到困惑之前因为我认为你只能放入一个目录。谢谢大家的帮助。

for i, v in enumerate(directories):
newpath = "/Users/simonorlovsky/code/carleton_archive/newsRelease/directories/"+v #path to current folder
files = os.listdir( newpath )
os.mkdir(v)
if files == []: #Check to make sure this directory isn't empty
    print v, "is empty"
directories[v] = files
print "Folder:", v
print "Files:", directories[v]
filesToCopyOver = directories[v]
for i in range(len(filesToCopyOver)):
    filesToCopyOver[i]= filesToCopyOver[i][:-3]+"tif"
    src = "/Users/simonorlovsky/code/carleton_archive/newsRelease/tiffs/"+filesToCopyOver[i]
    dst = "/Users/simonorlovsky/code/carleton_archive/newsRelease/"+v
    if filesToCopyOver[i][0]!=".":
        shutil.move(src, dst)
        print "File moved from ", src, "to", dst

print ""