Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Parsing CSVs...
#4
skipinitialspace=True is required if you have spaces after your separator character
Output:
separator v CompanyName LTD, "[email protected],[email protected]" ^ whitespace
If you don't skip the initial space(s) the csv reader misses the starting quote which messes up parsing the rest of the line. Instead of three columns like this.
Output:
CompanyName LTD [email protected], [email protected]" 12234,56678
you end up with 5
Output:
CompanyName LTD "[email protected] [email protected]" "12234 56678"
Such a subtle and not obvious difference that has a big effect.
The newline='' in:
with open("my_magic.csv", "r", newline="") as f:
removes newline characters (\n) from the end of lines read from the file. I don't think this is really needed here. The csv reader ignores the newline characters. Setting the newline to '' when writing a csv file prevents the csv writer writing a blank line after each row(two newline characters at the end of each row). I think that only happens on Windows

I would read the file like this:
import csv

with open("test.csv", "r") as file:
    data = csv.reader(file, skipinitialspace=True)
    for company, emails, numbers, in data:
        emails = emails.split(",")
        numbers = numbers.split(",")
        print(company, emails, numbers)
Reply


Messages In This Thread
Parsing CSVs... - by ChLenx79 - Dec-12-2022, 02:39 PM
RE: Parsing CSVs... - by perfringo - Dec-12-2022, 04:00 PM
RE: Parsing CSVs... - by ChLenx79 - Dec-13-2022, 03:29 PM
RE: Parsing CSVs... - by deanhystad - Dec-13-2022, 07:39 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020