Search code examples
pythonwindowsio

How does python access the file from a right click on Windows


I've written a simple python script that takes a .csv file, rearranges it and spits out an excel file. My aim is to be able to right click on a .csv file in Windows and for it to generate an .xslx file. I've used PyInstaller to successfully create an .exe and I've used default programs editor to put my executable in the context menu when csv files are right clicked. What I can't figure out is how to do the I/O correctly.

What I have is :

import fileinput
import csv
try: 
    csv_filename = fileinput.filename()
    print(csv_filename)
except: print('no input')
with open(filename_csv, 'rt', newline='', encoding='utf8') as csvfile:
    # do stuff
# write xslx_filename

Which doesn't work.

How do I access the file windows passes me when I open a file?

Edit: Just to clear up confusion. If I hard code the location of a csv file, my script works just fine. My problem is how do I access the file that Windows (presumably) passes to my script when I right click on a csv file and choose to open with csv2xslx (my script).


Solution

  • Thanks to martineau above for the pointer. The following made it work:

    file = sys.argv[1]
    with open(file, 'rt', newline='', encoding='utf8') as csvfile:
        # do stuff
    # write xslx_filename
    

    I'm still not sure if that is the 'correct' way of doing it, but it works so I'm happy.