Read, clean and convert CSV and JSON in Python (no libraries needed)
You do not need pandas for everyday CSV and JSON jobs. Python's standard library handles most of them in a few lines. These are the recipes I reuse. 1. Read a CSV into dictionaries import csv with open ( "people.csv" , newline = "" , encoding = "utf-8-sig" ) as f : rows = list ( csv . DictReader ( f ) ) print ( rows [ 0 ] ) # {'id': '1', 'email': 'a@x.com'} newline="" lets the csv module handle…
You don't need pandas for everyday CSV and JSON tasks. Python's standard library can handle most of them with a few lines of code. Here are six reusable recipes that you can use:
1. Read a CSV file into dictionaries. Use the `csv.DictReader()` function to read the file and store the rows as dictionaries. Handle line endings with `newline=""` and decode the file using `utf-8-sig` to remove any invisible BOM that Excel might add. Convert values to integers or floats as needed.
2. Remove duplicate rows based on a specific column. Keep track of unique keys using a set and a list. Iterate through each row, normalize the key by stripping whitespace and converting to lowercase, and add it to the set if it's not already present. Append the row to the unique list. This will help you identify and remove duplicate entries.
3. Write the unique rows back to a new CSV file. Open a new file in write mode and create a `csv.DictWriter()` object with the same fieldnames as the original first row. Write the header and then write the unique rows to the file.
4. Convert a cleaned CSV file to JSON format. Use the `json.dump()` function to write the unique rows as JSON data to a new JSON file. Set `indent=2` for pretty printing and `ensure_ascii=False` to keep non-ASCII characters readable.
5. Convert JSON data to a CSV file. Load the JSON data using `json.load()`. If the data is a dictionary, wrap it in a list. Extract the column names by iterating through the first object and collecting all unique keys. Open a new CSV file and use `csv.DictWriter()` to write the header and the data rows. Convert nested lists or dictionaries to JSON text for each cell.
6. Handle bad data safely. Wrap your conversion functions in a try-except block to catch any ValueError exceptions. Provide a default value to use in case of conversion errors. This way, one bad row won't crash the entire job, and you can log or handle the skipped rows as needed.
Some common mistakes to avoid include opening the file without `newline=""` (which creates blank lines on Windows), not specifying the encoding (which breaks on non-English text), not considering case or whitespace differences when comparing strings, loading large files with `list()`, overwriting your only copy of the data, and forgetting to write to a new file first.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to