Search code examples
mysqlpython-3.xcsvioerror

IOError No such file or directory, but file does exist


The following program is used to read a CSV file and turn it into a MySQL insert statement:

import csv

openFile = open('test.csv', 'r')
csvFile = csv.reader(openFile)
header = next(csvFile)
headers = map((lambda x: "'"+x+"'"), header)
insert = 'INSERT INTO Table (' + ", ".join(headers) +", 'time_stamp'" +") VALUES "
for row in csvFile:
    values = map((lambda x: "'"+x.strip()+"'"), row)
    print (insert +"("+ ", ".join(values) +", getdate());" )
openFile.close()

I have made the following modifications in an attempt to get the program to work with multiple files instead of just listing the filename explicitly but keep getting an error saying IOError: [Errno 2] No such file or directory: 'Exact name of existing file.csv', when the file clearly exists as it is printing the exact filename. How can I edit the following code to get it to work for a group of files in a directory without getting said error?

import csv, os

path = 'C:/Users/August/Desktop/TripDetailFiles/test'
for csvFile in os.listdir(path):
    if csvFile.endswith('.csv'):
        openFile = open(csvFile)
    readFile = csv.reader(openFile)
    header = next(readFile)
    headers = map((lambda x: "'"+x+"'"), header)
    insert = 'INSERT INTO Table (' + ", ".join(headers) +", 'time_stamp'" +") VALUES "
    for row in csvFile:
        values = map((lambda x: "'"+x.strip()+"'"), row)
        print (insert +"("+ ", ".join(values) +", getdate());" )
    openFile.close()

Solution

  • The absolute path suggests to me that you're not running the script from inside that directory.

    I believe os.listdir is giving you only filenames not paths, and those filenames don't exist in the directory the script is running in. You need to concatenate the path and the filename!

    openFile = open(path + '/' + csvFile)