How do you read and write CSV files properly?
BeginnerConceptData formats, HTTP & REST APIs
Answer
import csv
with open("inventory.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["hostname"], row["ip"])
with open("report.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=["id", "severity", "detail"])
w.writeheader()
w.writerows(findings)
Open with newline="" or you get blank lines on Windows and broken quoted newlines. The csv module handles quoting of commas and quotes in fields; never build CSV with ",".join(...).
More on Data formats, HTTP & REST APIs
How do you read and write JSON, and what are the common gotchas?BeginnerWhy must you use `yaml.safe_load` rather than `yaml.load`?BeginnerHow do you load a multi-document Kubernetes YAML file?IntermediateHow do you make an HTTP request with `requests` the right way?BeginnerWhy use a `requests.Session`?IntermediateHow do you add retries with exponential backoff to `requests`?Intermediate