Question

The following code works on its own. I have created an executable with py2exe which isn't working. The script processes and sorts some csv files. If I put this code in the "dist" directory where the executable is run (so it has the same filepath depth from the csv files being processed), the code works; but the executable itself in that same directory doesn't work.

import glob
import os
import pandas as pd

current_dir = os.path.dirname(os.path.realpath(__file__))

directory = os.path.sep.join(current_dir.split(os.path.sep)[:-2])
csvfiles = os.path.join(directory, '*.csv')
for csvfile in glob.glob(csvfiles):
    filename = os.path.basename(csvfile)
    if '_sorted' in filename:
        print "Remove this file"
        os.remove(csvfile)

csvfiles = os.path.join(directory, '*.csv')
for csvfile in glob.glob(csvfiles):
    filename = csvfile
    df = pd.read_csv(filename)

    df = df[df["ORGANIZATION"]!="WPPL"]
    df = df.sort('MEETING START TIME')    
    #write new csv file
    df.to_csv(filename + '_sorted.csv', cols=["DATE","MEETING START TIME","MEETING END TIME","DESCRIPTION","ORGANIZATION","LOCATION"],index=False)

raw_input("Press enter to close")

Also the raw input statement isn't keeping the screen open so I can't really see what's going on.

thanks

Was it helpful?

Solution

Trying to access data files as relative paths off dirname(__file__) is a really bad idea, unless you only want to run the program in the build tree. If you want to be able to install and run the program—whether using py2exe or any other mechanism—you're just asking for trouble.

If you're trying to package files with the executable, the right way to do this is with either the data_files mechanism from py2exe, or, if you can install and use setuptools, the more powerful and flexible Package Resources mechanism.

If, on the other hand, you want the user to supply the CSV files after installing your app, you almost certainly don't want to make him put them into your app's directory. The usual thing to do is access them as relative paths off the current working directory. In other words, just use ., not dirname(__file__).

But, if you really want to do this… the problem is that __file__ is the filename of your main script—which of course isn't useful when you're running a bundled executable. You can use sys.argv[0] or sys.executable, depending on your use case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top