How to move only *.java files with python?
Question
I have such dir tree:
dir1 - dir2 - dir3 - file1.java - file2.java - file3.cpp
and I want to move only *.java files to brand new directory called 'java_files' in current directory. How to make it? I read shutil doc but ...
This:
def moveFiles() :
source = "."
destination = "java_files"
if os.path.isfile(source):
shutil.move(source, destination)
doesn't work at all ...
I don't want to use shells 'mv' instead !
EDIT:
I also tried this:
def moveFiles() :
source = "."
destination = "java_files"
dirList = os.listdir(source)
for fname in dirList:
if fname.endswith(".java") :
shutil.move(source, destination)
but it gives:
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'.
La solution
In this kind of cases, I use glob (which accepts wildcards and regular expressions)
#!/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)
Autres conseils
if source.endswith('.java'):
# do copy or move file
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow