I am amateur at python but I have a task of converting folder of csv to json files. I have this script working with specified CSV file but I have no idea how to make the script iterate thrue folder of csv and convert all of those csv to json. The original script:
JavaScript
x
27
27
1
import csv
2
import json
3
import pandas as pd
4
5
file = '/users/krzysztofpaszta/CSVtoGD/build-a-bridge.csv'
6
json_file = '/users/krzysztofpaszta/CSVtoGD/build-a-bridge.json'
7
8
#Odczyt pliku CSV
9
def read_CSV(file, json_file):
10
csv_rows = []
11
with open(file) as csvfile:
12
reader = csv.DictReader(csvfile)
13
field = reader.fieldnames
14
for row in reader:
15
csv_rows.extend([{field[i]:row[field[i]] for i in range(len(field))}])
16
convert_write_json(csv_rows, json_file)
17
18
#Zamiana CSV na JSON
19
def convert_write_json(data, json_file):
20
with open(json_file, "w") as f:
21
f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': ')))
22
f.write(json.dumps(data))
23
24
25
read_CSV(file,json_file)
26
27
someone will give me a hint?
Advertisement
Answer
You can use os functions, particularly os.listdir()
to iterate over files in the directory, and safely generate new names with os.path.splitext()
:
JavaScript
1
10
10
1
import os
2
3
DIRECTORY = "/path/to/dir"
4
5
for f in os.listdir(os.fsencode(DIRECTORY)):
6
fn = os.fsdecode(f)
7
pre, ext = os.path.splitext(fn)
8
if ext == ".csv":
9
read_CSV(fn, pre + '.json')
10
The similar approach with pathlib would be:
JavaScript
1
11
11
1
from pathlib import Path
2
3
DIRECTORY = "/path/to/dir"
4
5
files = Path(DIRECTORY).glob('*.csv') # to process files only in this dir
6
7
files = Path(DIRECTORY).rglob('*.csv') # to process files in sub-directories recursively
8
9
for f in files:
10
read_CSV(f, str(f.with_suffix('.json'))) # use .with_suffix() for safe name generation
11