2

I have a Python script which opens a file and processes the contents ultimately creating a separate output file that I need to provide to other individuals. The problem is that this script will need to be run every day, and the file I open with the script will not have the same filename every day. So I know I can't hardcode the filename into the csv.reader(open(...) portion of the script.

While I could always just rename the file I receive to match the filename hardcoded into the script, this is not ideal as I would have to do this every day and I would be manipulating the original file, which is not ok. I am hoping there is an easy solution to modify my script to either open any file that ends with a particular extension (i.e. - .csv), or maybe there is a GUI solution via tkinter or wxpython that I could use to create a simple browse for file interface that will pass the name of the file selected into the portion of the script that opens the file.

Here's a sample of my script that I need to fix:

import csv

bs_ref = csv.reader(open('inputfile_14022011.csv','rb'))

<rest of script then processes the contents of the imported file but is not relevant to the question>

I would like to replace 'inputfile_14022001.csv' with something that allows any filename to potentially be called for that specific part of the script. Unfortunately, I haven't been able to find anything useful for creating a file browser interface that can be used to pass the selected filename to a specific portion of my script.

Thank you for any help someone can provide.

2
  • Are you looking for an interactive solution (with a GUI), or are you looking for something that can run unattended (such as "pick the latest inputfile_*.csv file")? Feb 14, 2011 at 21:21
  • Good question. Probably interactive so that I know the proper file is being processed. There is a ton of data being processed so checking it after the script finishes wouldn't be an easy task. Feb 15, 2011 at 0:16

2 Answers 2

4

Since you tagged wxpython, it can be something like this (untested) fragment:

from wxPython.wx import *
...
application = wxPySimpleApp()
...
dialog = wxFileDialog ( None, style = wxOPEN )
if dialog.ShowModal() == wxID_OK:
   print 'Selected:', dialog.GetPath()
   bs_ref = csv.reader(open(dialog.GetPath(),'rb'))
1
  • I tried this out and it looks like it's working perfectly! Thank you very much. I appreciate your quick reply. Feb 15, 2011 at 0:17
1
import glob

possible_filenames = glob.glob("*.csv")

# If you expect there to be only ONE file...
the_filename = possible_filenames[0]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.