1

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?

2
  • Does this answer your question? Writing CSV with `csv.DictWriter` results in empty lines between filled data lines Commented Oct 16, 2021 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 minimal reproducible example. 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. Commented Oct 16, 2021 at 14:24

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
This actually helps because this way there are always empty lines which at least is consistent

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.