0

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?

Atlantic
  • 11
  • 4
  • Does this answer your question? [Writing CSV with \`csv.DictWriter\` results in empty lines between filled data lines](https://stackoverflow.com/questions/49833283/writing-csv-with-csv-dictwriter-results-in-empty-lines-between-filled-data-lin) – wovano Oct 16 '21 at 14:20
  • There seem to be some typos in your question (for example, the output should be `['1', '2', '3', '4', '5']` instead of `['1', 'y', '3', '4', '5']`, and you seem to be mixing `x` and `y` throughout the text). Also, your question could be a lot shorter if you'd create a [mre]. Basically, your original CSV contents + your two code blocks combined + the final output would be sufficient to ask this question. The part about replacing values is not really relevant for the question and is only distracting. – wovano Oct 16 '21 at 14:24

1 Answers1

0

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

  • Welcome to Stack Overflow, Patrik. It's helpful that you found this answer, however, it's better to flag the question as duplicate than to copy the answer. This way, all current and future answers can more easily be found, and the voting system will help us decide what's the most useful answer. – wovano Oct 16 '21 at 14:18
  • This actually helps because this way there are always empty lines which at least is consistent – Atlantic Oct 16 '21 at 14:28