Writerow In Python 3 Writes Me Always A Blank Line Beetween The Origin Lines, Python2 Works Great. Why?
I have trouble with my Code. in Python2 I use withopen to print something in a csv, it works great. When i Use Python 3 i have to remove the BinaryMode (wb) an then it always print a blank line beetween the correct lines. Why ?
with open('C:\\Users\\KDD1SGM\\Desktop\\example\\exportPython3.csv', mode="wb") as out:
writer = csv.writer(out, delimiter=";")
writer.writerow(writeData)
for i in range(len(newfunctions)):
writer.writerow(newfunctions[i])
and the output is as follows:
line1: 1,2,3
line2: 4,5,6
....
when i try to remove the Binary Mode in with open (for Python3) the output csv is:
line1: 1,2,3
line2: 4,5,6
line3: ...
why is there a blank line now ? and how to remove it ?
Answer
In Python 2, if you open out
with mode 'wb'
then csv.writer
writes \r\n
into the file directly. It will write \r\r\n
only if you open it in binary mode, because on Windows it will translate each \n
into \r\n
.
In Python 3 fortunately the syntax changed, so open out
with the additional parameter newline=''
instead to avoid any hassle.
Example:
with open('C:\\Users\\KDD1SGM\\Desktop\\example\\exportPython3.csv', mode="w", newline='') as out:
writer = csv.writer(out, delimiter=";")
writer.writerow(writeData)
for i in range(len(newfunctions)):
writer.writerow(newfunctions[i])
Sources
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module