I am trying to create a text file of the path and file name of everything within a certian directory. After looking around, it looks like the best way to do this is with the GLOB function and I was able to write a code that got me a list of the paths to every file:
import glob
dirlist = glob.glob('P:\MyDep\Myunit\MySection\Stuff\Reports\YR*\O*\*\*\*\*.pdf')
Bureau\Traffic\Reports\YR*\R*\*\*.pdf')
fo=open('new.txt', "w")
fo.write('\n'.join(dirlist))
fo.close()
However, I found myself using excell’s MID statment to extract values from the report. Ideally, I would like the basename of the file inclued with the path as a tuple. I’ve come up with the the following:
for f in glob.glob('P:\MyDep\Myunit\MySection\Stuff\Reports\YR*\O*\*\*\*\*.pdf'):
fpath, fname = os.path.split(f)
rname, extname = os.path.splitext(fname)
dirtup = (f, rname)
print dirtup
But I cannot seem to write the results to a text file: the best I can seem to do is generate a text file with one listing from dirtup (edited to show code w/sugestions):
import glob, os
for f in f in glob.glob('P:\MyDep\Myunit\Mysection\Stuff\Reports\YR*\O*\*\*\*\*.pdf'):
fpath, fname = os.path.split(f)
rname, extname = os.path.splitext(fname)
dirtup = (f, rname)
fo=open('axlspd.txt', "w")
fo.write(', '.join(dirtup)+'\n')
fo.close()
How can I get the all the results of dirtup into a text file? Thanks in advance.
The problem is that you open the file multiple times. With the ‘w’ flag, the file is truncated each time it is opened, and you would only see the last write.
Open the file before the loop, and close it after, or use the new-fangled with statement:
The file is automatically closed when you exit that block of code.
This is the reference you missed: http://docs.python.org/library/functions.html#open