0

我有这样的目录树:

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'.
4

2 回答 2

2
if source.endswith('.java'):
    # do copy or move file
于 2012-08-20T15:21:17.393 回答
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)
于 2012-08-20T15:23:53.160 回答