Reputation: 55
I'm attempting to convert JSON data into a csv with tempfile and am receiving a "no such file or directory" error.
testjson = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
def sso():
# Add SQL Here
# Creates a temp dir
tempdir = tempfile.mkdtemp()
path = os.path.join(tempdir)
with open(path + '/temp.json', 'w') as fp:
json.dump(testjson, fp)
# Changes the data to CSV
def json_to_csv(path, fileInput, fileOutput):
inputFile = open(path + fileInput)
data = json.load(inputFile)
inputFile.close()
with open(os.path.join(path, fileOutput), 'w') as fp:
output = csv.writer(fp)
output.writerow(data[0].keys())
for row in data:
output.writerow(row.values())
json_to_csv(path, '/testjson.json', '/xxx.csv')
The full errors are: line 47, in sso json_to_csv(path, '/testjson.json', '/xxx.csv')
line 38, in json_to_csv inputFile = open(path + fileInput)
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\CHRIS~1\AppData\Local\Temp\tmp8mc6dxup/testjson.json'
To be perfectly honest, I am quite new to programming and python. I found these code blocks from an article that neatly described exactly what I need to do. (Take Json, convert to csv, and email it through lambda.) I would be so grateful for any insight.
Upvotes: 0
Views: 130
Reputation: 17301
try using os.path.join()
when merging pathnames, so the interpreter doesn't get confused about mismatched path separators.
testjson = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
def sso():
tempdir = tempfile.mkdtemp()
path = os.path.join(tempdir, 'temp.json')
with open(path, 'w') as fp:
json.dump(testjson, fp)
# Changes the data to CSV
def json_to_csv(path, fileInput, fileOutput):
data = json.load(open(os.path.join(path, fileInput)))
with open(os.path.join(path, fileOutput), 'w') as fp:
output = csv.writer(fp)
output.writerow(data[0].keys())
for row in data:
output.writerow(row.values())
json_to_csv(tempdir, 'testjson.json', 'xxx.csv')
Upvotes: 1