Model df.to_csv(index=False): write a table as CSV with minimal quoting, as pandas does.
What to build
A program that writes rows as correctly quoted CSV.
Requirements
- Print the header and every row with fields joined by commas.
- A field that contains a comma or a double quote is wrapped in double quotes, and each double quote inside it is doubled. The field
NaNis written as an empty field. Other fields are written as they are.
Input
Line 1: n. Line 2: the header, fields separated by semicolons. Then n rows, fields separated by semicolons.
Output
n + 1 lines.
Constraints
1 ≤ n ≤ 100; fields contain no semicolons or newlines.
Example
Input:
3
name;city
Ana;Paris
Smith, John;London
Bob "B";NaN
Output:
name,city
Ana,Paris
"Smith, John",London
"Bob ""B""",
Why it works
Quoting only the fields that need it keeps the file readable, and doubling quotes inside a quoted field lets a reader tell an embedded quote from the end of the field.
Examples
3 name;city Ana;Paris Smith, John;London Bob "B";NaN
name,city Ana,Paris "Smith, John",London "Bob ""B""",
1 a 1
a 1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
A field needs quotes when it contains a comma or a double quote.
Hint 2
Inside quotes, every double quote is written twice.
Hint 3
The value NaN is written as an empty field.
Solution
Show one correct solution (try it yourself first)
def field(v):
if v == "NaN":
return ""
if "," in v or '"' in v:
return '"' + v.replace('"', '""') + '"'
return v
n = int(input())
print(",".join(field(v) for v in input().split(";")))
for _ in range(n):
print(",".join(field(v) for v in input().split(";")))