如何用python移动* .java文件?

时间:2012-08-20 15:18:49

标签: python directory shutil

我有这样的目录树:

dir1
 - dir2
 - dir3
 - file1.java
 - file2.java
 - file3.cpp

我想只将* .java文件移动到当前目录中名为“java_files”的全新目录。怎么做?我读了shutil doc但是......

此:

def moveFiles() :
    source = "."
    destination = "java_files"
    if os.path.isfile(source):
        shutil.move(source, destination)

根本不起作用......

我不想使用shell'mv'代替!

编辑:

我也试过这个:

def moveFiles() :
    source = "."
    destination = "java_files"
    dirList = os.listdir(source)
    for fname in  dirList:
        if fname.endswith(".java") :
            shutil.move(source, destination)

但它给出了:

File "test.py", line 95, in <module>
 main()   File "test.py", line 91, in main
 moveFils()   File "test.py", line 82, in move
 shutil.move(source, destination)   File "/usr/lib/python2.7/shutil.py", line 295, in move
 raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst) shutil.Error:Cannot move a directory '.' into itself 'java_files'.

2 个答案:

答案 0 :(得分:2)

if source.endswith('.java'):
    # do copy or move file

答案 1 :(得分:1)

在这种情况下,我使用glob(接受通配符和正则表达式)

#!/usr/bin/env python

import glob
import shutil
import os

source="."
destination = "/tmp/newDestination/"

if not(os.path.exists(destination)):
    os.makedirs(destination)
elif not(os.path.isdir(destination)):
    raise OSError("Kabooom! The destination %s exists, but is not a directory" % destination)

for javaFile in glob.glob(os.path.join(source, "*.java")):
    if os.path.isfile(javaFile):
        shutil.move(os.path.abspath(javaFile), destination)