
The advantage of CSV files is simplicity.
Can’t have images or charts embedded in them. Don’t have settings for font size or color. Don’t have types for their values-everything is a string. You can download example.csv from or enter the text into a text editor and save it as example.csv.ĬSV files are simple, lacking many of the features of an Excel spreadsheet. I will use this file for this chapter’s interactive shell examples. For example, the spreadsheet example.xlsx from would look like this in a CSV file: The csv ModuleĮach line in a CSV file represents a row in the spreadsheet, and commas separate the cells in the row. (JSON is short for JavaScript Object Notation.) You don’t need to know the JavaScript programming language to use JSON files, but the JSON format is useful to know because it’s used in many web applications. JSON (pronounced “JAY-sawn” or “Jason”-it doesn’t matter how because either way people will say you’re pronouncing it wrong) is a format that stores information as JavaScript source code in plaintext files. Python’s csv module makes it easy to parse CSV files. But Python also comes with the special csv and json modules, each providing functions to help you work with these file formats.ĬSV stands for “comma-separated values,” and CSV files are simplified spreadsheets stored as plaintext files. You can view them in a text editor, such as Mu. CSV and JSON files, on the other hand, are just plaintext files. These files were in a binary format, which required special Python modules to access their data. Output: data.json Conversion 100.000 rows completed successfully in 0.In Chapter 15, you learned how to extract text from PDF and Word documents.
Print(f"Conversion 100.000 rows completed successfully in seconds")
JsonString = json.dumps(jsonArray, indent=4) With open(jsonFilePath, 'w', encoding='utf-8') as jsonf: #convert python jsonArray to JSON String and write to file #load csv file data using csv library's dictionary reader With open(csvFilePath, encoding='utf-8') as csvf:
For the test I made 100.000 lines in a csv file with copy/paste, and the whole conversion takes about half a second with Apple's M1 Chip while the presented example took only 0.0005 seconds.ĭef csv_to_json(csvFilePath, jsonFilePath):. You may write the JSON String to a JSON file. Convert the Python List to JSON String using json.dumps(). Add the dictionary to the Python List created in step 1.
Read the lines of CSV file using csv.DictReader() function.To convert CSV to JSON in Python, follow these steps: