Reading files in from the proper directory

Peter Otten __peter__ at web.de
Tue Feb 7 13:59:05 EST 2012


SMac2347 at comcast.net wrote:

> Hello. I am admittedly a Python novice, and ran into some trouble
> trying to write a program that will pull multiple excel files all into
> one file, with each file on a different sheet.
> 
> I am confident most of the code is correct, as the program runs
> without any errors and I found the base of it online, making changes
> as necessary for my own purposes. 

That confidence usually evaporates once you write the first unit test ;)

> However, I am having trouble
> specifying the exact directory where my code should be pulling the
> files from. All the files are in the same folder, and I have put the
> folder on my desktop. Am I correct in thinking that I need to change
> the current working directory to this folder in order for Python to
> read in these files, then generate my output? Or should I be doing
> something else?

Do it properly, allow specifying the files on the commandline:

import argparse

def process_files(files, destfile):
    # put your real code here
    print "merge " + "\n      ".join(files)
    print "into  " + destfile

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("files", metavar="file", nargs="+")
    parser.add_argument("destfile")
    args = parser.parse_args()
    process_files(args.files, args.destfile)

If you have standard locations for sources and destination you can wrap your 
python script into a little batch file containing something like

python \source\path\*.xls \dest\path\merged.xls

and invoke that to get both flexibility and convenience.




More information about the Python-list mailing list