Convert all CSV files in a given directory to JSON using Python I am attempting to convert all files with the csv extension in a given directory to json with this python script. 

I am wondering if there is a better and more efficient way to do this?

Here is my code:

import csv
import json
import glob
import os

for filename in glob.glob('//path/to/file/*.csv'):
    csvfile = os.path.splitext(filename)[0]
    jsonfile = csvfile + '.json'

    with open(csvfile+'.csv') as f:
        reader = csv.DictReader(f)
        rows = list(reader)

    with open(jsonfile, 'w') as f:
        json.dump(rows, f)


EDIT:

Here is the sample input:



Here is the sample output:

[{
"username": "lanky",
"user_id": "4",
"firstname": "Joan",
"middlename": "Agetha",
"lastname": "Lanke",
"age": "36",
"usertype": "admin",
"email": "lanke.joan.wind@gmail.com"
}, {
"username": "masp",
"user_id": "56",
"firstname": "Mark",
"middlename": "Patrick",
"lastname": "Aspir",
"age": "25",
"usertype": "member",
"email": "aspirman@gmail.com"
}]
Looks good to me. It's a perfectly sensible approach.

There's just one line I'm going to criticize:

    csvfile = os.path.splitext(filename)[0]


Picking off element zero is fine, no need to change it. Other idiomatic approaches would be name, ext = ..., or an explicit discard of name, _ = ....

What I really do advocate changing is the identifier csvfile, since the .csv extension has been stripped from it. Better to simply call it name. Then an expression like name + '.csv' can be clearly seen as a csvfile expression.

You could elide the jsonfile assignment, if you like, and similarly rows, replacing each reference with the expression.