[Python-talk] Beginning of a cheesy file navigator... Why does it do ...
Bruce Labitt
bruce.labitt at myfairpoint.net
Fri Jul 3 13:52:32 EDT 2009
I have the beginnings of a file navigation module that I want to embed
in some other code I have written. Umm, it almost works. Here is the
latest version. Questions at bottom.
==== start code ===============================================
#!/usr/bin/env python
import shutil
import sys, os, string
"""
Program to navigate to proper data file
Author: Bruce Labitt
Copyright 2009 by Bruce Labitt
Date: 3 July 2009
"""
def myfilenavigate( ):
currentdir = os.getcwd() # save current directory
baddir = 1
while (baddir ==1):
dirflag = 1
while (dirflag==1):
try:
yorn = raw_input('Is your data in the default drive? (y) or n ==> ')
if (yorn == 'n'):
mydatadir = raw_input('Enter the data subdir ==> ')
# use double \ for directory separators. why? that's what
works...
else:
mydatadir = 'c:\\Python25\\mytec'
os.chdir(mydatadir) # change directory to mydatadir
except (IOError, NameError):
print 'Subdirectory does not exist, try again!'
mydatadir = raw_input('Enter a valid data subdirectory ==> ')
else:
dirflag = 0
print 'Listing of data subdirectory'
os.system('dir *.dat') # DOS system command
rightdir = raw_input('In the right dir? (y) or n ==> ')
if (rightdir =='n'):
baddir = 1
dirflag = 1
else:
baddir = 0 # set to get out of baddir loop
badfile = 1
print
while (badfile == 1): # stay in loop until we get a good file name
try:
filename = raw_input('Enter filename ==> ')
f1 = open(filename, 'rb')
except (IOError, NameError):
print 'File does not exist, try again!'
else:
print 'File opened for reading'
badfile = 0 # gets out of loop
os.chdir(currentdir) # put the directory back
return f1
==== end code
===============================================================
Here is a snippet of the run:
===============================================
In [13]: %run tecgtreadermb.py
Is your data in the default drive? (y) or n n
Enter the data subdir ==> g:\python_stuff
Listing of data subdirectory
Volume in drive G has no label.
Volume Serial Number is 0000-1F3B
Directory of g:\python_stuff
11/10/2008 05:57 PM 3,199,616 test.dat
1 File(s) 3,199,616 bytes
0 Dir(s) 1,558,749,184 bytes free
In the right dir? (y) or n ==> n
Listing of data subdirectory
Volume in drive G has no label.
Volume Serial Number is 0000-1F3B
Directory of g:\python_stuff
11/10/2008 05:57 PM 3,199,616 test.dat
1 File(s) 3,199,616 bytes
0 Dir(s) 1,558,749,184 bytes free
In the right dir? (y) or n ==>
================================================
As you can see, taking the non-default path results in going thru the
while(baddir==1) loop, but not thru the while(dirflag==1) loop?
Can anyone point me in the right direction?
If I take the defaults, everything seems to work as expected...
-Bruce
More information about the Python-talk
mailing list