0

So what I've done is created an HTML form with which I can submit CSV files that are then handled by a Python script.

Further, I will very likely be creating the filenames of each CSV file dynamically in the following format: YYYY-MM-DD HH.MM.SS.csv.

Is there any way to retrieve the filename of the submitted CSV file so that I can open the file in a manner depicted below?

with open('????-??-?? ??.??.??.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['first_name'], row['last_name'])

Below is what the form looks like, and I know I can pass the filename forward using get, but there has to be a way to do it with post...

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <form action="process-excel.py" method="post" enctype="multipart/form-data">
            <input type="file" name="myFile">
        </form>
    </body>
</html>

process-excel.py

Bear in mind that the script below is just an old template I kept for using PyMySQL to insert data into a database.

# -*- coding: utf-8 -*-
import pymysql.cursors
import csv


""" HOW DO I RETRIEVE THE FILENAME OF A FILE THAT IS SUBMITTED
''' FROM <input type="file" name="myFile"> IN THE FORM ABOVE?
"""

with open('names.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['first_name'], row['last_name'])


con = pymysql.Connect(host='localhost',
                    user='',
                    password='',
                    db='',
                    charset='utf8mb4',
                    cursorclass=pymysql.cursors.DictCursor)

try:
    with con.cursor() as cursor:
        sql = "INSERT INTO `test` (`title`, `description`, `category`) VALUES (%s, %s, %s)"
        cursor.execute(sql, ('a', 'b', 'c'))
        con.commit()
except Exception:
    raise Exception('INSERT FAILED..................................')
oldboy
  • 5,729
  • 6
  • 38
  • 86
  • Where's the code that is handling the upload? You should be able to get the filename from parsing the multipart form-data during the upload process. – Patrick Roberts Sep 17 '18 at 02:02
  • @PatrickRoberts i don't have a script yet. i'm completely new to all of this. first time using `CSV` and very new to Python in general. – oldboy Sep 17 '18 at 02:03
  • So `process-excel.py` does not exist? – Patrick Roberts Sep 17 '18 at 02:04
  • @PatrickRoberts it does basically as a blank slate. ive added one of my old templates that ill likely be using as a foundation – oldboy Sep 17 '18 at 02:05
  • Where's your server? None of that is server code, just a database client. – Patrick Roberts Sep 17 '18 at 02:06
  • @PatrickRoberts um... it will be running on the server that i'm paying for. are these questions leading to anything? – oldboy Sep 17 '18 at 02:07
  • What you're referring to is most likely a remote hosting service, not a server. You _write_ the server. If you didn't, you would not be writing code to open an uploaded CSV file. Take a look at a basic example using Flask: https://stackoverflow.com/questions/40414526/how-to-read-multipart-form-data-in-flask – Patrick Roberts Sep 17 '18 at 02:13
  • @PatrickRoberts dude, all i need to know is how to retrieve the filename of the file that was submitted via the form so that i can insert it into my database??? – oldboy Sep 17 '18 at 02:15
  • You're asking something that doesn't even make sense. You can't open a file if you don't have code for uploading it, and the code for uploading it is where you would be able to access the filename. – Patrick Roberts Sep 17 '18 at 02:17
  • @PatrickRoberts omg dude do you not see the HTML form? thats whats used to submit/upload the file to the server... – oldboy Sep 17 '18 at 02:18
  • It's very clear from this conversation that you don't know what a server is. Try submitting the form. See what happens. If there's no server to process the upload, nothing but an error page will occur. After you're finished with that realization, check out some popular server frameworks for Python like [Django or Flask](https://www.google.com/search?q=python+server+frameworks) so you can handle the upload and get the filename. – Patrick Roberts Sep 17 '18 at 02:21
  • @PatrickRoberts youre obvs not understanding. when i submit the form, it takes me to a blank page because my `process-excel.py` script is blank since i havent done anything with it so far. all im trying to do is figure out how to retrieve the name of the CSV file that is submitted via the HTML form in the python file... are you trying to say that i cant pass the file from the HTML form to the python script to be handled by the python script?? – oldboy Sep 17 '18 at 02:25
  • You're obviously not understanding. HTML forms don't just execute random Python files on a remote host. You have to write a _server_ that accepts HTTP requests and creates HTTP responses. Please look at either of the two links I've provided and write a server that handles a POST request to the path `/process-excel.py`. From there you can get a request object from the server framework you end up using and access the filename and data of the uploaded file. – Patrick Roberts Sep 17 '18 at 02:29
  • man, why is it so complicated with python? maybe ill just use PHP to handle the file. i figured since i can pass files to PHP files i should be able to pass them to Python files, but i guess not. what exactly do you mean by im going to have to write a "server"??? can i not just send the file to a PHP file which triggers a Python script to process the file? – oldboy Sep 17 '18 at 02:32
  • PHP scripts are executed by a server framework called [Apache](http://httpd.apache.org/), not by random clients uploading forms. You run an Apache server and configure it to listen to a particular TCP port on the host, through which clients can make requests to the server, which are handled by PHP scripts. In other languages like Node.js or Python, you have to set up a server and configure it, much like you do with Apache. – Patrick Roberts Sep 17 '18 at 02:35
  • yes, my server is running apache which executes the php script. i was referring to the value of the `action` attribute of the HTML form... again, ive purchased hosting thru a 3rd party, so i dont have root access and limited control over the server, but im obvsiously still able to execute python and php scripts. – oldboy Sep 17 '18 at 02:38
  • If you're using Apache, it would be best to continue writing in PHP then. Otherwise I would contact the hosting service and ask them what your options are for running a Django or Flask server if you really want to use Python and not PHP. – Patrick Roberts Sep 17 '18 at 02:40
  • @PatrickRoberts i really have no issues against using both of them. anyways, the only reason im using python at all is because im scraping data off of the web with it, and sticking it into an excel file, which i planned to manually submit to my website via an HTML form, in order to avoid a bunch of hassles/extraneous costs such as getting my own server back up and running, scraping the data on there, and then purchasing a new internet connection to get a dedicated IP so that i can host it myself. – oldboy Sep 17 '18 at 02:45

0 Answers0