Home > Software engineering >  Empty rows in python generated csv
Empty rows in python generated csv

Time:10-17

I'm working on a custom keyboard. I am using .csv file to store what are the individual key bindings. The csv for it looks like this:

1,2,3,4,5
q,w,e,r,t
a,s,d,f,g
z,x,c,v,b
6,7,8,9,0
y,u,i,o,p

Now, I have a function that reads the file and puts it in a list:

import csv
bMap = []
# initial fillout of bMap
f = open('bMap.csv', 'r')
contents = csv.reader(f, delimiter=',', quotechar='|')
for row in contents:
    bMap.append(row)
f.close()
print(bMap)

And this is my output:

[['1', 'y', '3', '4', '5'], ['q', 'w', 'e', 'r', 't'], ['a', 's', 'd', 'f', 'g'], ['z', 'x', 'c', 'v', 'b'], ['6', '7', '8', '9', '0'], ['y', 'u', 'i', 'o', 'p']]

So far, so good. Now let's say that the user changes the binding of '2' to 'x'

bMap[0][1] = 'y'
print(bMap)

Of course, the output is the same as list time but with 'x' instead of '2'.

Now I want it to save the changes to the aformentioned .csv file. I am using the following function:

f = open('bMap.csv', 'w')
writer = csv.writer(f, delimiter=',', quotechar='|')
writer.writerows(bMap)
f.close()

Now, when i open the csv file, it looks as follows:

1,y,3,4,5

q,w,e,r,t

a,s,d,f,g

z,x,c,v,b

6,7,8,9,0

y,u,i,o,p

I have these empty lines for some reason. Now if I run the code again it won't work properly. How can I get rid of them? Why are they being written at all?

CodePudding user response:

The solution to your problem is simple. Just change this line accordingly.

f = open('bMap.csv', 'w', newline='')

For more info, check the link below.

Specify Newline character ('\n') in reading csv using Python

  • Related