I’ve recently started learning python and am having some trouble. The functions in question attempt to start at a given directorty, in my case, ‘/home/jesse/ostest’, search through all of the sub-directories, and copy all ‘.txt’ files to ‘/home/jesse/COPIES’. When I run the program, a few files get coppied but it gets stuck in an infinite loop. I’d like it to break when it changes to ‘/home/jesse’ (10th line of search()). Maybe I’m not understanding recursion that well but help is appreciated.
Here is a test directory, with subdirectries to test the program.
[jesse@jesse ostest]$ tree
.
├── readme.txt
├── README_WxPython.txt
├── rect.txt
├── RELEASE_NOTES.txt
├── scrap.txt
├── sndarray.txt
├── sprite.txt
├── surface.txt
├── surfarray.txt
├── test_oo.txt
├── tests.txt
├── this
│ ├── gme_notes.txt
│ ├── gme_readme.txt
│ ├── h1.txt
│ ├── h2.txt
│ ├── how_to_build.txt
│ ├── howto_release_pygame.txt
│ ├── image.txt
│ ├── IMPORTANT_MOVED.txt
│ ├── index.txt
│ ├── install.txt
│ ├── is
│ │ ├── a
│ │ │ ├── color.txt
│ │ │ ├── common.txt
│ │ │ ├── cursors.txt
│ │ │ ├── dec.txt
│ │ │ ├── defs.txt
│ │ │ └── display.txt
│ │ ├── event.txt
│ │ ├── examples.txt
│ │ ├── filepaths.txt
│ │ ├── font.txt
│ │ ├── freetype.txt
│ │ ├── gfxdraw.txt
│ │ ├── gme_design.txt
│ │ └── path
│ │ ├── api.txt
│ │ ├── auth.txt
│ │ ├── camera.txt
│ │ ├── cdrom.txt
│ │ ├── cert_override.txt
│ │ ├── changes_for_symbian.txt
│ │ └── CHANGES.txt
│ └── joystick.txt
├── time.txt
├── TODO.txt
└── transform.txt
4 directories, 45 files
Here is the code:
def copyAll():
print('This function attempts to search through /home/jesse/ostest and copy all .txt files.')
input('Press <enter> to begin..')
new = '/home/jesse/COPIES'
os.mkdir(new)
done = []
search('/home/jesse/ostest', new, done)
print(os.getcwd())
print(os.listdir())
def search(arg, new, done):
os.chdir(arg)
print(os.getcwd())
for var in os.listdir():
if os.path.isdir(var) and var not in done:
search(var, new, done)
elif var[-4:] == '.txt' and var not in done:
shutil.copy2(var, '/home/jesse/COPIES')
print('COPIED', var, '\t\tto', new)
elif os.getcwd() == '/home/jesse':
break
else:
done += os.getcwd()
os.chdir('..')
search(os.getcwd(), new, done)
Start by taking a look at os.walk():
http://docs.python.org/2/library/os.html#os.walk