Search code examples
pythonpython-2.7argvsys

Python 3 - FileNotFoundError: [Errno 2] No such file or directory


I am trying to modify a script to take in arguments so I can run the script and it cycles through a number of csv files and produces the results.

However I am falling down early on when trying to just run the what was working code with an argument instead of hard coded using sys.argv instead of schema.csv

I am running the script out of the code directory which is where the schema.csv is but I am getting this error.

FileNotFoundError: [Errno 2] No such file or directory: "['schema.csv']"

I have double checked the working directory with os.getcwd(), my thought is that the result highlighted in the error has too many quotation marks or brackets but I am not sure on what I can test.

import sys


def get_schema(table):

    with open(str(sys.argv[1:])) as f:
        i = 0
        for line in f:
            column = line.split(',')
            datatype='STRING'
            if (column[0] == table):
                if 'char' in column[2]:
                    datatype = 'STRING'
                elif 'int' in column[2]:
                    datatype = 'INTEGER'
                elif 'boolean' in column[2]:
                    datatype = 'BOOLEAN'                
                elif 'timestamp' in column[2]:
                    datatype = 'TIMESTAMP'
                elif 'numeric' in column[2]:
                    datatype = 'NUMERIC'
                elif 'date' in column[2]:
                    datatype = 'DATE'              
                if (i == 0):
                    print('#%s' %(table))
                    print ('[')
                    i = i + 1
                if (i == 1):
                    print ('{"name":"%s", "mode": "NULLABLE", "type": "%s"}' %(column[1],datatype))
                if (i > 1):
                    print (',{"name":"%s", "mode": "NULLABLE", "type": "%s"}' %(column[1],datatype))
                i = i + 1
        print(',{"name":"ExtractAuditKey", "mode": "NULLABLE", "type": "INTEGER"}')
        print (']')


get_schema(table=(sys.argv[1:]))

FileNotFoundError: [Errno 2] No such file or directory: "['schema.csv']"

Solution

  • with open(str(sys.argv[1:])) as f: will not work as you hope here. You're using sys.argv[1:] which gives you a list by "slicing", rather than a string. If you're only inputting one value, you can do sys.argv[1] instead and it should work - indexing gives the entry, slicing gives a list.