Python Forum
CSV gives me blank row on PC, but not a Mac
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
CSV gives me blank row on PC, but not a Mac
#1
I am using the following code write a CSV file from a List containing Dictionaries

When I run it on my Mac it is fine, but when I run it on a PC I get blank rows between each data line. Why is this? I had to add the utf-8 otherwise the Windows file path did not work. Is this related to the issue?

def print_report():
    order = ['id', 'Sub Estate', 'hostname', 'type', 'os', 'lastSeenAt', 'Last_Seen', 'health', 'threats', 'service_health', 'tamperProtectionEnabled', 'ipv4Addresses', 'associatedPerson']
    with open(report_path, 'w', encoding='utf-8') as output_file:
        dict_writer = csv.DictWriter(output_file, order)
        dict_writer.writeheader()
        dict_writer.writerows(computer_list)
Also, I would like to only output some of these keys. Is there a way to do this or do I have output them all?

Thanks in advance.
Reply
#2
Try:
with open(report_path, 'w', encoding='utf-8', newline='') as output_file:
Reply
#3
As stated in the docs:
Quote: If csvfile is a file object, it should be opened with newline=''.
and the footnote:
Quote:If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.

That's exactly the case with Windows where lineendings are \r\n
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

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