import csv# read CSVwith open("data.csv", "r") as file: reader = csv.reader(file) for row in reader: print(row)#ans: row is a list
import csv# read with headerswith open("data.csv", "r") as file: reader = csv.DictReader(file) for row in reader: print(row["name"], row["age"])
import csv# write CSVdata = [["Name", "Age"], ["Alice", 25]]with open("out.csv", "w", newline="") as file: writer = csv.writer(file) writer.writerows(data)
import json# read JSON filewith open("data.json", "r") as file: data = json.load(file)#ans: returns dict or list
import json# write JSON filedata = {"name": "Alice", "age": 25}with open("out.json", "w") as file: json.dump(data, file, indent=2)
import json# to JSON stringdata = {"name": "Alice"}json_str = json.dumps(data)#ans: '{"name": "Alice"}'#ans: from JSON stringdata = json.loads(json_str)#ans: {"name": "Alice"}
import csv# csv.reader returns?with open("data.csv") as f: reader = csv.reader(f) row = next(reader)#ans: row is a list
import csv# DictReader first row?#ans: first row is headers
import csv# writerows vs writerow?writer.writerows([[1,2],[3,4]])#ans: writes 2 rowswriter.writerow([1,2])#ans: writes 1 row
import json# load vs loads?json.load(file) # from filejson.loads(string) # from string
import json# dump vs dumps?json.dump(data, file) # to filejson.dumps(data) # to string
import json# indent parameter?json.dumps({"a": 1}, indent=2)#ans: pretty-printed with 2 spaces
import json# JSON with Python types?json.dumps([1, "text", True, None])#ans: '[1, "text", true, null]'
import csv# newline="" why?open("file.csv", "w", newline="")#ans: prevents extra blank lines
import json# can JSON handle tuples?json.dumps((1, 2, 3))#ans: "[1, 2, 3]" (becomes array)
import csv# CSV delimiter?csv.reader(file, delimiter=";")#ans: use semicolon instead of comma
Google tag (gtag.js)